在python中创建一个由列表索引的字典 [英] Create a dictionary in python which is indexed by lists

查看:359
本文介绍了在python中创建一个由列表索引的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个由列表索引的字典。例如,我的字典应该如下所示:

I would like to create a dictionary which is indexed by lists. For instance, my dictionary should look like:

D = {[1,2,3]:1, [2,3]:3}

任何人都知道如何做到这一点?如果我只输入 D([1,2,3])= 1 ,则返回错误。

Anyone know how to do this? If I just type D([1,2,3]) = 1 it returns an error.

推荐答案

dict键必须是可哈希的,哪些列表不是因为它们是可变的。您可以在完成列表后更改列表。想想当用作键的数据变化时,尝试保留一个dict是多么棘手?这没有任何意义。想象这种情况

dict keys must be hashable, which lists are not becase they are mutable. You can change a list after you make it. Think of how tricky it would be to try to keep a dict when the data used as keys changes; it doesn't make any sense. Imagine this scenario

>>> foo = [1, 2]
>>> bar = {foo: 3}
>>> foo.append(4)

,您将看到为什么Python不尝试将列表作为键。

and you will see why Python does not try to support lists as keys.

最明显的解决方案是使用元组而不是列表作为键。

The most obvious solution is to use tuples instead of lists as keys.

>>> d = {[1, 2, 3]: 1, [2, 3]: 3}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> d = {(1, 2, 3): 1, (2, 3): 3}
>>> d
{(2, 3): 3, (1, 2, 3): 1}
>>> d[2, 3]
3

这篇关于在python中创建一个由列表索引的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆