开发者

How to use index as a key in Python?

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 th开发者_开发技巧at:

x[open(v)] = 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


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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜