Python的列表索引必须是整数,而不是元组“

Python 'list indices must be integers, not tuple"

我已经用头撞了这两天了。我不熟悉Python和编程,所以这种类型的错误的其他示例对我帮助不大。我正在阅读文档中的列表和元组,但没有找到任何有用的东西。任何一个指针都会受到赞赏。不一定要寻找答案,只是在哪里寻找更多的资源。我使用的是python 2.7.6。谢谢

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
measure = raw_input("How would you like to measure the coins? Enter 1 for grams 2 for pounds. ")

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']
]

if measure == 2:
    for coin, coin_weight, rolls, worth in coin_args:
        print"Enter the weight of your %s" % (coin)
        weight = float(raw_input())
        convert2grams = weight * 453.592

        num_coin = convert2grams / (float(coin_weight))
        num_roll = round(num_coin / (float(rolls)))
        amount = round(num_coin * (float(worth)), 2)

        print"You have %d %s, worth $ %d, and will need %d rolls." % (num_coin, coin, amount, num_roll)

else:
    for coin, coin_weight, rolls, worth in coin_args:
        print"Enter the weight of your %s" % (coin)
        weight = float(raw_input())

        num_coin = weight / (float(coin_weight))
        num_roll = round(num_coin / (float(rolls)))
        amount = round(num_coin * (float(worth)), 2)

        print"You have %d %s, worth $ %d, and will need %d rolls." % (num_coin, coin, amount, num_roll)

这是堆栈跟踪:

1
2
3
File".\coin_estimator_by_weight.py", line 5, in <module>
  ["nickles", '5.0', '40.0', '.05']
TypeError: list indices must be integers, not tuple


问题是,python中的[...]有两个不同的含义

  • expr [ index ]表示访问列表的元素
  • [ expr1, expr2, expr3 ]表示从三个表达式中建立一个三个元素的列表。
  • 在代码中,您忘记了外部列表中项目的表达式之间的逗号:

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

    因此,python将第二个元素的开头解释为要应用于第一个元素的索引,这就是错误消息所说的。

    您要查找的内容的正确语法是

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

    要创建列表列表,需要用逗号分隔它们,如下所示

    1
    2
    3
    4
    5
    6
    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']
    ]


    为什么错误提到了元组?

    其他人解释说问题是缺少的,,但最后的谜团是为什么错误消息会谈论元组?

    原因是你的:

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

    可以简化为:

    1
    [][1, 2]

    如6502所述,误差相同。

    但随后,处理[]决议的__getitem__object[1, 2]转换为一个元组:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    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)

    对于列表内置类,__getitem__的实现不能处理这样的元组参数。

    更多有关__getitem__操作的示例,请访问:https://stackoverflow.com/a/33086813/895245