Reshape An Irregular List In Python
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']
Solution 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.
Solution 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']]
Solution 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.
Post a Comment for "Reshape An Irregular List In Python"