reshape an irregular list in python

扶醉桌前 提交于 2021-02-10 14:29:45

问题


I would like to reshape the following list :

wide_list = [[1,['a','b','c']],[2,['d','e']],[3,'f']]

in a "long format":

long_list = [[1,'a'],[1,'b'],[1,'c'],[2,'d'],[2,'e'],[3,'f']]

How can this be achieved efficiently in Python?


回答1:


Try a nested list comprehension:

>>> wide_list = [[1,['a','b','c']],[2,['d','e']],[3, ['f']]]
>>> long_list = [[k, v] for k, sublist in wide_list for v in sublist]
>>> long_list
[[1, 'a'], [1, 'b'], [1, 'c'], [2, 'd'], [2, 'e'], [3, 'f']]

Note, the last group had to be changed to match the pattern of the first two groups. Instead of [3, 'f'], use [3, ['f']] instead. Otherwise, you'll need special case logic for groups that don't follow the pattern.




回答2:


One way this can be done is using a list comprehension:

>>> [[x[0],letter] for x in wide_list for letter in x[1]]
[[1, 'a'], [1, 'b'], [1, 'c'], [2, 'd'], [2, 'e'], [3, 'f']]



回答3:


Using list comprehensions,

long_list = [[x[0],item] for x in wide_list for item in x[1]]

However, this answer is probably the most clear.



来源:https://stackoverflow.com/questions/7882997/reshape-an-irregular-list-in-python

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