Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表中多个目录的zip dict.items()?_Python_Dictionary_Zip_Items - Fatal编程技术网

Python 列表中多个目录的zip dict.items()?

Python 列表中多个目录的zip dict.items()?,python,dictionary,zip,items,Python,Dictionary,Zip,Items,我认为这应该很容易,但找不到一个简单而优雅的解决方案。 我有这个: l = [{1: 1, 2: 2}, {'a': 'a', 'b': 'b'}] 我想要这个: l = [((1, 1), ('a', 'a')), ((2, 2), ('b', 'b'))] 如何将列表中多个dict的项压缩在一起?Python 3 在Python3中,dict.items返回一个dict\u items对象。要防止出现这种情况,可以通过执行以下操作将它们全部转换为元组: list(zi

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

l = [{1: 1, 2: 2},
     {'a': 'a', 'b': 'b'}]
我想要这个:

l = [((1, 1), ('a', 'a')),
     ((2, 2), ('b', 'b'))]
如何将列表中多个dict的项压缩在一起?

Python 3 在Python3中,
dict.items
返回一个
dict\u items
对象。要防止出现这种情况,可以通过执行以下操作将它们全部转换为元组:

list(zip(*map(dict.items, l)))
list(map((lambda d: tuple(d.items())), l))
# Or with multiple maps:
list(map(tuple, map(dict.items, l))))
其中
zip(*)
将iterable扩展为
zip
的参数,然后
zip
将参数压缩为元组(有效地将所有值转换为元组)

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

list(zip(*map(dict.items, l)))
list(map((lambda d: tuple(d.items())), l))
# Or with multiple maps:
list(map(tuple, map(dict.items, l))))
可以说,这更直观,但确实使用了
lambda
或多个映射,因此对于较小的词典列表来说效率较低

Python 2 在Python 2中,
dict.items
返回一个
列表
。如果您不特别需要列表上的元组,那么将它们保持为列表就可以了,并且
map(dict.items,l)
就足够了

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

zip(*map(dict.items, l))
您还可以简单地映射
元组

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

类似于
zip(*map(dict.items,l))
。请注意,字典中键的顺序可能会改变。这正是我所需要的,也可以与OrderedICT一起工作以保持秩序。请作为答案发布。@barrios我们输出列表的顺序重要吗?是的。我想知道理解是否可以达到同样的效果?