将Python列表和Dict理解与计数器结合使用 [英] Combine Python List and Dict comprehension with counter

查看:44
本文介绍了将Python列表和Dict理解与计数器结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要转移一个元组列表:

I want to transfer a list of tuples:

[(1, 3, 5), (2, 4, 6), (7, 8, 9)]

dict 的列表(以创建熊猫数据框),如下所示:

to a list of dict (in order to create a pandas dataframe) which looks like:

[{'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)]

如何实现?

推荐答案

您可以使用列表理解使用第二个 for 遍历'match' es:

You can use list comprehension use a second for to loop over the 'match'es:

[{'index':ind, 'match':match} for ind,s in enumerate(test_set,1) for match in s]

因此,第二个 for 循环遍历元组中的元素,并为这些元素中的每个元素生成一个字典并将其添加到结果中.

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.

这篇关于将Python列表和Dict理解与计数器结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆