Combine Python List and Dict comprehension with counter

僤鯓⒐⒋嵵緔 提交于 2021-02-17 02:22:30

问题


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:

[{'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?


回答1:


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]

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.



来源:https://stackoverflow.com/questions/42486563/combine-python-list-and-dict-comprehension-with-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!