将Python List和Dict理解与计数器结合起来

J-H*_*J-H 1 python dictionary list-comprehension list

我想传输一个元组列表:

[(1, 3, 5), (2, 4, 6), (7, 8, 9)]
Run Code Online (Sandbox Code Playgroud)

dict(为了创建一个pandas数据帧)的列表,看起来像:

[{'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}]
Run Code Online (Sandbox Code Playgroud)

出于性能原因,我想使用列表和字典理解:

[{'index':ind, 'match': } for ind, s in enumerate(test_set, 1)]
Run Code Online (Sandbox Code Playgroud)

怎么能实现这一目标?

Wil*_*sem 7

您可以使用列表推导使用秒for来循环'match'es:

[{'index':ind, 'match':match} for ind,s in enumerate(test_set,1) for match in s]
Run Code Online (Sandbox Code Playgroud)

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