2017-02-27 54 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

非常感謝。正是我在找什麼。 –