[英]Combine Python List and Dict comprehension with counter
I want to transfer a list of tuples: 我想转移一个元组列表:
[(1, 3, 5), (2, 4, 6), (7, 8, 9)]
to a list of dict
(in order to create a pandas dataframe) which looks like: 到
dict
列表(以创建熊猫数据框),如下所示:
[{'index':1, 'match':1},{'index':1, 'match':3},{'index':1, 'match':5},
{'index':2, 'match':2}, {'index':2, 'match':4},{'index':2, 'match':6},
{'index':3, 'match':7},{'index':3, 'match':8},{'index':3, 'match':9}]
For performance reasons I wanted to use a list and dict comprehension: 出于性能原因,我想使用列表和字典理解:
[{'index':ind, 'match': } for ind, s in enumerate(test_set, 1)]
How can this be achieved? 如何做到这一点?
You can use list comprehension use a second for
to loop over the 'match'
es: 您可以使用列表理解,使用第二个
for
循环遍历'match'
match'es:
[{'index':ind, 'match':
match} for ind,s in enumerate(test_set,1)
for match in s]
So the second for
loop iterates over the elements in the tuples and for each of these elements, a dictionary is generated and added to the result. 因此,第二个
for
循环遍历元组中的元素,并为每个这些元素生成一个字典并将其添加到结果中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.