问题
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