Unpack List Of Lists Into List
I have list of lists of tuples: a = [[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10)]] How can I make one list of tuples: b = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)] Naive way is: b
Solution 1:
Using itertools
demo:
import itertools
a = [[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10)]]
print(list(itertools.chain(*a)))
Output:
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
Solution 2:
You don't want to append, you want to extend. You can use the really simple loop
a = [[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10)]]
single_level_list = []
for lst in a:
single_level_list.extend(lst)
print(single_level_list)
>>> [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
Solution 3:
This operation is called 'flatten' in some of other languages. In python, followings method might be shortest.
a = [[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10)]]
sum(a, [])
// [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
It also work in the case the parent list have many child lists.
b = [[1],[2],[3],[4],[5]]
sum(b, [])
// [1, 2, 3, 4, 5]
Post a Comment for "Unpack List Of Lists Into List"