简体   繁体   English

需要一个值为两个列表的 defaultdict

[英]Need a defaultdict with values as two lists

In Python, I want something like在 Python 中,我想要类似的东西

dict = defaultdict((list,list))

Essentially, with every key I want two lists!本质上,每个键我都想要两个列表!

With the above snippet I get the error first argument must be callable.使用上面的代码片段,我得到错误第一个参数必须是可调用的。 How can I achieve this ?我怎样才能做到这一点?

Give as parameter to defaultdict a function that creates your empty lists:defaultdict一个创建空列表的函数作为参数:

from collections import defaultdict

def pair_of_lists():
    return [[], []]

d = defaultdict(pair_of_lists)

d[1][0].append(3)
d[1][1].append(42)

print(d)
# defaultdict(<function pair_of_lists at 0x7f584a40b0d0>, {1: [[3], [42]]})

It is not some kind of type inference, you just provide a function that generates default value.它不是某种类型推断,您只是提供一个生成默认值的函数。 While int , list , dict without argument generate 0 , [] , {} , which is often exploited in defaultdict declaration.而没有参数的intlistdict生成0[]{} ,这在 defaultdict 声明中经常被利用。 Python has no build in constructor function for pair of list etc. So it is as simple as Python 没有内置的构造函数用于列表对等。所以它很简单

di = defaultdict(lambda : ([1,2,3], ['a', 'cb']))

While Python allows tuples (pairs) of lists, you might have some issues eg with hashing of list tuples.虽然 Python 允许列表元组(对),但您可能会遇到一些问题,例如列表元组的散列。 To be safe, you can set deafult to list of two list.为了安全起见,您可以将默认设置为两个列表的列表。 Note you have set it to specific lists, empty or not, and not list type/constructor.请注意,您已将其设置为特定列表,无论是否为空,而不是列表类型/构造函数。 It is literally about setting default value and not a type declaration - python lists are untyped.它实际上是关于设置默认值而不是类型声明——python 列表是无类型的。

from collections import defaultdict
l1 = []
l2 = ["another", "default", "list"]
di = defaultdict(lambda : [ l1, l2] )
print (di[3])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM