2017-02-27 55 views
1

我想元组的列表传输:结合Python的列表和字典的理解与反

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

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}] 

出于性能方面的原因,我想用一个列表和字典理解:

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

如何CA这可以实现吗?

+1

这是你在那里的元组列表;没有套。 –

+0

你说绩效很重要。在这种情况下,嵌套的for循环无法理解,不是吗? – Elmex80s

+0

@ Elmex80s:你可以在列表理解中使用嵌套for循环。 –

回答

7

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

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

所以第二for循环迭代的元组的元素和这些元素,字典生成并添加到结果中。

+1

非常感谢。正是我在找什么。 –