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

Aar*_*ron 35 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)
Run Code Online (Sandbox Code Playgroud)

这是堆栈跟踪:

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

650*_*502 63

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

  1. expr [ index ] 表示访问列表的元素
  2. [ expr1, expr2, expr3 ] 意味着从三个表达式构建三个元素的列表

在您的代码中,您忘记了外部列表中项目的表达式之间的逗号:

[ [a, b, c] [d, e, f] [g, h, i] ]
Run Code Online (Sandbox Code Playgroud)

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

您正在寻找的正确语法是

[ [a, b, c], [d, e, f], [g, h, i] ]
Run Code Online (Sandbox Code Playgroud)


the*_*eye 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']
]
Run Code Online (Sandbox Code Playgroud)


Cir*_*四事件 9

为什么错误提到了元组?

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

原因是你的:

["pennies", '2.5', '50.0', '.01'] 
["nickles", '5.0', '40.0', '.05']
Run Code Online (Sandbox Code Playgroud)

可以简化为:

[][1, 2]
Run Code Online (Sandbox Code Playgroud)

正如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)
Run Code Online (Sandbox Code Playgroud)

并且__getitem__列表内置类的实现不能处理像这样的元组参数.

我还建议你在将来尝试制作最少的例子:-)

更多__getitem__行动示例:https://stackoverflow.com/a/33086813/895245