Python 作为字典键的列表

Python 作为字典键的列表,python,Python,我有多个元组列表,例如 [([1, 2, 3, 4], 2), ([5, 6, 7], 3)] 我希望将其作为字典的键(因此字典中的每个键都是元组列表) 不幸的是,根据我得到的TypeError(unhabable-type:list),python似乎不喜欢哈希列表。我的元组列表中的所有元素都是int(如果有区别的话)。对我能做什么有什么建议吗?谢谢 改用元组 >>> dict((tuple(x[0]), x[1]) for x in [([1,2,3,4],2),([5,

我有多个元组列表,例如

[([1, 2, 3, 4], 2), ([5, 6, 7], 3)]
我希望将其作为字典的键(因此字典中的每个键都是元组列表)

不幸的是,根据我得到的
TypeError
unhabable-type:list
),python似乎不喜欢哈希列表。我的元组列表中的所有元素都是int(如果有区别的话)。对我能做什么有什么建议吗?谢谢

改用元组

>>> dict((tuple(x[0]), x[1]) for x in [([1,2,3,4],2),([5,6,7],3)])
{(5, 6, 7): 3, (1, 2, 3, 4): 2}

您应该将列表转换为元组

>>> def nested_lists_to_tuples(ls):
    return tuple(nested_lists_to_tuples(l) if isinstance(l, (list, tuple)) else l for l in ls)

>>> nested_lists_to_tuples([([1,2,3,4],2),([5,6,7],3)])
(((1, 2, 3, 4), 2), ((5, 6, 7), 3))
然后使用返回的值作为密钥。请注意,我这样做是为了让您能够支持更深层的元组和列表嵌套混合,如
[([1,(2,[3,4,[5,6,(7,8)])、3,4],2),([5,6,7],3)]


不过,可能有一种更简单的方法可以做到这一点。

使用
repr

class A:
    pass

import time

# A and time as heterogenous elements, only to show the generality of my solution

li_li = [ [([1,2,3,4],2),([5,6,7],3)] ,
          [([10,20,3],2),      ([5,6,77],3)] ,
          [([1,2,3,4],2),([5,6,time,7],3),([875,12], ['jk',78], A, (100,23),'zuum')] ]




didi = {}
for i,li in enumerate(li_li):
    didi[repr(li)] = i

print 'dictionary  didi:'
for k,v in didi.iteritems():
    print k,'     ',v

print '----------------------------------'

print didi[repr([([1+1+1+1+1+5,         200000/10000,    3],2),([5,8-2,7*11],3)      ])]
结果

dictionary  didi:
[([1, 2, 3, 4], 2), ([5, 6, <module 'time' (built-in)>, 7], 3), ([875, 12], ['jk', 78], <class __main__.A at 0x011CFC70>, (100, 23), 'zuum')]       2
[([1, 2, 3, 4], 2), ([5, 6, 7], 3)]       0
[([10, 20, 3], 2), ([5, 6, 77], 3)]       1
----------------------------------
1
字典滴滴: [1,2,3,4,2],[5,6,7,3],[875,12],[jk',78],[100,23],[zuum')]2 [([1, 2, 3, 4], 2), ([5, 6, 7], 3)] 0 [([10, 20, 3], 2), ([5, 6, 77], 3)] 1 ---------------------------------- 1.
将列表转换为元组:

dict((tuple(a), b) for a,b in [([1,2,3,4],2),([5,6,7],3)])
如果您使用的是Python>=2.7,则可以使用dict理解:

{tuple(a): b for a,b in [([1,2,3,4],2),([5,6,7],3)]}

因为元组是不可变的。不幸的是,不可变并不总是等于。可变并不总是意味着不可更改。仅供参考,很容易理解为什么不能使用列表作为字典的键:如果修改它们呢?字典需要哈希类型作为键的原因是为了以后能够识别键。
{tuple(a): b for a,b in [([1,2,3,4],2),([5,6,7],3)]}