[英]Combine Python List and Dict comprehension with counter
我想轉移一個元組列表:
[(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)]
如何做到這一點?
您可以使用列表理解,使用第二個for
循環遍歷'match'
match'es:
[{'index':ind, 'match':match} for ind,s in enumerate(test_set,1) for match in s]
因此,第二個for
循環遍歷元組中的元素,並為每個這些元素生成一個字典並將其添加到結果中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.