S
Sergio Correia
Hi,
I'm looking for an easy way to flatten a two level list like this
spam = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
Into something like
eggs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
There are *no* special cases (no empty sub-lists).
I have found two ways:
1) Accumulator
eggs = []
for x in eggs:
eggs.extend(x)
2) Reduce
eggs = reduce(lambda x, y: x+y, spam)
I feel the 1st way is too cumbersome (three lines), and although I
like the 2nd way (except for the lambda part), I understand reduce is
discouraged by Guido so I want to know if there is a "Better Way"(TM)
?
Any ideas?
Thanks,
Sergio
PS: Why does `sum` works only with numbers?
I'm looking for an easy way to flatten a two level list like this
spam = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
Into something like
eggs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
There are *no* special cases (no empty sub-lists).
I have found two ways:
1) Accumulator
eggs = []
for x in eggs:
eggs.extend(x)
2) Reduce
eggs = reduce(lambda x, y: x+y, spam)
I feel the 1st way is too cumbersome (three lines), and although I
like the 2nd way (except for the lambda part), I understand reduce is
discouraged by Guido so I want to know if there is a "Better Way"(TM)
?
Any ideas?
Thanks,
Sergio
PS: Why does `sum` works only with numbers?