gpt4 book ai didi

python - zip dict.items() 列表中的多个字典?

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:25 26 4
gpt4 key购买 nike

我认为这应该很容易,但找不到简单而优雅的解决方案。我有这个:

l = [{1: 1, 2: 2},
{'a': 'a', 'b': 'b'}]

我想要这个:

l = [((1, 1), ('a', 'a')),
((2, 2), ('b', 'b'))]

如何将多个字典的项目压缩到一个列表中?

最佳答案

python 3

在 Python 3 中,dict.items返回 dict_items目的。为防止这种情况,您可以通过执行以下操作将它们全部变成元组:

list(zip(*map(dict.items, l)))

在哪里zip(*<iterable>)正在将 iterable 扩展为 zip 的参数然后 zip会将参数压缩为元组(有效地将所有值转换为元组)。

然而,这在过程中非常冗余地构建了多个列表。这可以通过以下方式避免:

list(map((lambda d: tuple(d.items())), l))
# Or with multiple maps:
list(map(tuple, map(dict.items, l))))

可以说,这更直观,但确实使用了 lambda或多个 map ,因此对于较小的字典列表效率较低。

python 2

在 Python 2 中,dict.items返回 list .如果你不特别需要一个元组覆盖一个列表,将它们作为一个列表保存就可以了,map(dict.items, l)就足够了。

在这里,您可以执行与上面相同的操作(省略 list(...),因为 zip 返回一个列表:

zip(*map(dict.items, l))

您也可以简单地映射 tuple .

map(tuple, map(dict.items, l))
# Or with a lambda:
map((lambda d: tuple(d.items())), l)

关于python - zip dict.items() 列表中的多个字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com