如何在Python中使用索引作为键?

发布于 2024-12-08 04:07:52 字数 263 浏览 2 评论 0原文

我有一个列表: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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

深空失忆 2024-12-15 04:07:52

问题是键必须是不可变的,而列表则不然。然而,元组是。

简单地将 v 转换为元组:

x[tuple(v)] = 7

详细来说,上面与编写相同

x[1,2,2,3] = 7

,后者是语法变体

x[(1,2,2,3)] = 7

The problem is that keys must be immutable, which lists are not. Tuples, however, are.

Simply convert v to a tuple:

x[tuple(v)] = 7

To elaborate, the above is the same as writing

x[1,2,2,3] = 7

and the latter is a syntactic variation of

x[(1,2,2,3)] = 7
一向肩并 2024-12-15 04:07:52

Python 有两种类似的数据结构来存储值列表。 list 是可变版本:它的值可以更改。

x = [1, 2, 2, 3]
x = list((1, 2, 3, 4))

tuple 是不可变的版本。一旦创建,其值就无法修改。

x = 1, 2, 2, 3
x = (1, 2, 2, 3)
x = tuple((1, 2, 2, 3))

Python 不允许您使用可变类型作为字典键,因此您只需将元组创建为列表:

x[tuple(v)] = 7

Python has two similar data structures for storing lists of values. list is the mutable version: its values can be changed.

x = [1, 2, 2, 3]
x = list((1, 2, 3, 4))

tuple is the immutable version. Once created, its value can't be modified.

x = 1, 2, 2, 3
x = (1, 2, 2, 3)
x = tuple((1, 2, 2, 3))

Python doesn't let you use mutable types as dictionary keys, so you just need to create your tuple to a list:

x[tuple(v)] = 7
兰花执着 2024-12-15 04:07:52

字典键必须是可哈希的。列表不可散列,但元组可以。 (对象的哈希值在对象的生命周期内永远不应该改变。此外,两个可哈希的值比较相等的对象必须具有相同的哈希值。由于列表是可变的,因此满足这两个条件的唯一方法是使所有列表返回相同的哈希值,而不是允许这种情况并破坏哈希值的目的,Python 让所有可变容器。不可散列。)

x[tuple(v)]

x[1,2,2,3] 之所以有效,是因为元组是 使用逗号表示,而不是括号:

In [78]: 1,2,2,3
Out[78]: (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[tuple(v)]

x[1,2,2,3] works because a tuple is indicated by the use of commas, not the parentheses:

In [78]: 1,2,2,3
Out[78]: (1, 2, 2, 3)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文