mat*_*teo 4 python python-3.x defaultdict
我有2个示例列表,我想要实现的是获取具有值总和的嵌套默认字典.
以下代码很好用:
from collections import defaultdict
l1 = [1,2,3,4]
l2 = [5,6,7,8]
dd = defaultdict(int)
for i in l1:
for ii in l2:
dd[i] += ii
Run Code Online (Sandbox Code Playgroud)
但我要做的是在d字典中创建一个默认密钥:
from collections import defaultdict
l1 = [1,2,3,4]
l2 = [5,6,7,8]
dd = defaultdict(int)
for i in l1:
for ii in l2:
dd[i]['mykey'] += ii
Run Code Online (Sandbox Code Playgroud)
这会抛出一个错误:
Traceback (most recent call last):
File "/usr/lib/python3.6/code.py", line 91, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "<string>", line 12, in <module>
TypeError: 'int' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)
基本上我无法理解的是,是否有机会混合defaultdict(dict)和defaultdict(int).
你想要一个默认的整数dict的默认字典:
dd = defaultdict(lambda: defaultdict(int))
Run Code Online (Sandbox Code Playgroud)
运行代码后:
>>> dd
{1: defaultdict(<class 'int'>, {'mykey': 26}),
2: defaultdict(<class 'int'>, {'mykey': 26}),
3: defaultdict(<class 'int'>, {'mykey': 26}),
4: defaultdict(<class 'int'>, {'mykey': 26})}
Run Code Online (Sandbox Code Playgroud)
defaultdict数据结构接收将提供默认值的函数,因此如果要创建defautdict(int)默认值,则提供执行此操作的函数,例如lambda : defaultdict(int):
from collections import defaultdict
from pprint import pprint
l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
dd = defaultdict(lambda : defaultdict(int))
for i in l1:
for ii in l2:
dd[i]['mykey'] += ii
pprint(dd)
Run Code Online (Sandbox Code Playgroud)
产量
defaultdict(<function <lambda> at 0x7efc74d78f28>,
{1: defaultdict(<class 'int'>, {'mykey': 26}),
2: defaultdict(<class 'int'>, {'mykey': 26}),
3: defaultdict(<class 'int'>, {'mykey': 26}),
4: defaultdict(<class 'int'>, {'mykey': 26})})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |