Python 为什么列表索引必须是整数,而不是元组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4784054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:30:07  来源:igfitidea点击:

Why list indices must be integers, not tuple?

pythonlistdictionarytuples

提问by Roman

I have this simple program:

我有这个简单的程序:

x = {}
x[1,2] = 3
print x
print x[1,2]

It works fine. The fist printgenerates {(1,2):3}and the second one generates 3.

它工作正常。拳头print生成{(1,2):3},第二个生成3

But in my "big" program I seems to do the same but get a list indices must be integers, not tupleerror. What this error message can mean and how I can resolve this problem?

但是在我的“大”程序中,我似乎也做了同样的事情,但出现了list indices must be integers, not tuple错误。此错误消息可能意味着什么以及如何解决此问题?

采纳答案by unwind

If you're getting that error, then you are trying to index a list, and not a dictionary.

如果您收到该错误,那么您正在尝试索引一个列表,而不是一个字典。

A Python list, like [1, 2, 3], must be indexed with integer values. A dictionary, which is what you have in your example, can be indexed by a wider range of different values.

Python 列表,如[1, 2, 3],必须使用整数值进行索引。您在示例中拥有的字典可以通过更广泛的不同值进行索引。

回答by Andrew Jaffe

Note that x={}defines xto be a dictionary, not a list (which can have any hashable as a key, and with syntactic sugar that translates d[key1,key2]to d[(key1,key2)]).

请注意,x={}定义x是一个字典,而不是一个列表(它可以有任何可散列的作为键,并带有转换d[key1,key2]为 的语法糖d[(key1,key2)])。

See, however, numpy, which allows multidimensional arrays if that's really what you want.

但是,请参阅numpy,如果这确实是您想要的,它允许多维数组。

回答by lightning2911

x = {}

This creates a dictionary, not a list.

这将创建一个字典,而不是一个列表。

x[1,2] = 3

assigns the value 3 to the key (1, 2) a tuple.

将值 3 赋给键 (1, 2) 一个元组。

A list can only be indexed by integers. Maybe you have mixed up the [] und {} using your dict?

列表只能由整数索引。也许您使用字典混淆了 [] 和 {}?