【发布时间】:2022-10-07 23:39:44
【问题描述】:
我知道以前有人问过类似的问题,但我找不到适合我的情况的答案。
假设我有以下元组列表:
d = [('first', 1), ('second', 2), ('third', 3)]
我可以很容易地将其转换为字典:
dict(d)
# {'first': 1, 'second': 2, 'third': 3}
现在,如果我有以下元组列表:
d = [('a', 'first', 1), ('a', 'second', 2), ('b', 'third', 3)]
我怎样才能最有效地获得以下嵌套字典:
{'a': {'first': 1, 'second': 2}, 'b': {'third': 3}}
这是我现在的解决方案:
from collections import defaultdict
dd = defaultdict(dict)
for a, b, c in d:
dd[a][b] = c
# defaultdict(dict, {'a': {'first': 1, 'second': 2}, 'b': {'third': 3}})
这是执行此操作的最高效方式吗?是否可以避免for循环?
很可能我必须处理d 非常大的情况,并且这种方法可能无法很好地扩展。这部分对我正在构建的 Web 应用程序至关重要,这就是性能非常重要的原因。
输入/反馈/帮助表示赞赏!
【问题讨论】:
-
您可以避免显式的
for循环,但某种形式的循环是不可避免的。 -
我相信你是对的。但是,如果我必须选择,那么我会比我自己更信任 python 来执行循环。
标签: python python-3.x list python-collections