如何在Python中使用索引作为键?
我有一个列表:v = [1,2,2,3]
。我想用这个列表作为钥匙。我可以“手动”完成:
x = {}
x[1,2,2,3] = 7
但是
x[v] = 7
不起作用。完成我需要做的事情最简单的方法是什么?
添加
我想象解决方案是这样的:
x[open(v)] = 7
I have a list: v = [1,2,2,3]
. I would like to use this list as a key. I can do it "manually":
x = {}
x[1,2,2,3] = 7
But
x[v] = 7
does not work. What is the easiest way to do what I need to do?
ADDED
I imagine the solution as something like that:
x[open(v)] = 7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是键必须是不可变的,而列表则不然。然而,元组是。
简单地将
v
转换为元组:详细来说,上面与编写相同
,后者是语法变体
The problem is that keys must be immutable, which lists are not. Tuples, however, are.
Simply convert
v
to a tuple:To elaborate, the above is the same as writing
and the latter is a syntactic variation of
Python 有两种类似的数据结构来存储值列表。
list
是可变版本:它的值可以更改。tuple
是不可变的版本。一旦创建,其值就无法修改。Python 不允许您使用可变类型作为字典键,因此您只需将元组创建为列表:
Python has two similar data structures for storing lists of values.
list
is the mutable version: its values can be changed.tuple
is the immutable version. Once created, its value can't be modified.Python doesn't let you use mutable types as dictionary keys, so you just need to create your tuple to a list:
字典键必须是可哈希的。列表不可散列,但元组可以。 (对象的哈希值在对象的生命周期内永远不应该改变。此外,两个可哈希的值比较相等的对象必须具有相同的哈希值。由于列表是可变的,因此满足这两个条件的唯一方法是使所有列表返回相同的哈希值,而不是允许这种情况并破坏哈希值的目的,Python 让所有可变容器。不可散列。)
x[1,2,2,3]
之所以有效,是因为元组是 使用逗号表示,而不是括号:Dict keys must be hashable. Lists are not hashable, but tuples are. (A hash value of an object should never change during the life of the object. Moreover, two hashable objects which compare equal must have the same hash. Since lists are mutable, the only way to satisfy both conditions would be to make all lists return the same hash value. Rather than allowing this and subverting the purpose of hashes, Python make all mutable containers unhashable.)
x[1,2,2,3]
works because a tuple is indicated by the use of commas, not the parentheses: