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

时间:2014-02-09 17:40:50

标签: python list

我两天来一直在反对这个问题。我是python和编程的新手,所以这类错误的其他例子对我没什么帮助。我正在阅读列表和元组的文档,但是没有找到任何有用的东西。任何指针都将非常感激。没有必要寻找答案,只需要更多的资源来查看。我使用的是Python 2.7.6。感谢

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)

这是堆栈跟踪:

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

3 个答案:

答案 0 :(得分:57)

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

  1. expr [ index ]表示访问列表元素
  2. [ expr1, expr2, expr3 ]表示构建三个表达式中三个元素的列表
  3. 在您的代码中,您忘记了外部列表中项目的表达式之间的逗号:

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

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

    您正在寻找的正确语法是

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

答案 1 :(得分:12)

要创建列表列表,您需要用逗号分隔它们,例如

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

答案 2 :(得分:8)

为什么错误会提到元组?

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

原因是你的:

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

可以简化为:

[][1, 2]

mentioned by 6502,但错误相同。

但是后来处理__getitem__解析的[]会将object[1, 2]转换为元组:

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