我有一个列表字典,我想将它们合并成一个名称元组列表。我想要第一个元组中所有列表的第一个元素,第二个元素在第二个元组中等等。
示例:
{'key1': [1, 2, 3], 'key2': [4, 5, 6], 'key3': [7, 8, 9]}我希望得到的列表是这样的:
[('key1': 1, 'key2': 4, 'key3': 7),
('key1': 2, 'key2': 5, 'key3': 8),
('key1': 3, 'key2': 6, 'key3': 9)]我想有一种优雅的方法可以做到这一点?
编辑:
我比较了@Steve Jessop的名字和@Ashwini Chaudhary的字典版本的运行时间,前者的速度要快一些:
d = {key: numpy.random.random_integers(0, 10000, 100000)
for key in ['key1', 'key2', 'key3']}平均100次跑步中:
namedtuple and map: 0.093583753109
namedtuple and zip: 0.119455988407
dictionary and zip: 0.159063346386发布于 2021-10-15 00:57:54
根据乔杜里的回答,我开发了一个基于发电机的解决方案。这可能会有帮助,当迪克特是巨大的。
def zip_dict(d):
for vals in zip(*(d.values())):
yield dict(zip(d.keys(), vals))示例用法:
d = dict(
x=[1,3,5,7,9],
y=[2,4,6,8,10]
)
for t in zip_dict(d):
print(t)其结果将是:
{'x': 1, 'y': 2}
{'x': 3, 'y': 4}
{'x': 5, 'y': 6}
{'x': 7, 'y': 8}
{'x': 9, 'y': 10}https://stackoverflow.com/questions/21930705
复制相似问题