Python 'list indices must be integers, not tuple"

前端 未结 3 1986
南旧
南旧 2021-02-01 02:21

I have been banging my head against this for two days now. I am new to python and programming so the other examples of this type of error have not helped me to much. I am readin

相关标签:
3条回答
  • 2021-02-01 02:52

    To create list of lists, you need to separate them with commas, like this

    coin_args = [
        ["pennies", '2.5', '50.0', '.01'],
        ["nickles", '5.0', '40.0', '.05'],
        ["dimes", '2.268', '50.0', '.1'],
        ["quarters", '5.67', '40.0', '.25']
    ]
    
    0 讨论(0)
  • 2021-02-01 02:56

    The problem is that [...] in python has two distinct meanings

    1. expr [ index ] means accessing an element of a list
    2. [ expr1, expr2, expr3 ] means building a list of three elements from three expressions

    In your code you forgot the comma between the expressions for the items in the outer list:

    [ [a, b, c] [d, e, f] [g, h, i] ]
    

    therefore Python interpreted the start of second element as an index to be applied to the first and this is what the error message is saying.

    The correct syntax for what you're looking for is

    [ [a, b, c], [d, e, f], [g, h, i] ]
    
    0 讨论(0)
  • 2021-02-01 02:57

    Why does the error mention tuples?

    Others have explained that the problem was the missing ,, but the final mystery is why does the error message talk about tuples?

    The reason is that your:

    ["pennies", '2.5', '50.0', '.01'] 
    ["nickles", '5.0', '40.0', '.05']
    

    can be reduced to:

    [][1, 2]
    

    as mentioned by 6502 with the same error.

    But then __getitem__, which deals with [] resolution, converts object[1, 2] to a tuple:

    class C(object):
        def __getitem__(self, k):
            return k
    
    # Single argument is passed directly.
    assert C()[0] == 0
    
    # Multiple indices generate a tuple.
    assert C()[0, 1] == (0, 1)
    

    and the implementation of __getitem__ for the list built-in class cannot deal with tuple arguments like that.

    More examples of __getitem__ action at: https://stackoverflow.com/a/33086813/895245

    0 讨论(0)
提交回复
热议问题