Converting a list of lists to a single list

Terry Reedy tjreedy at udel.edu
Tue Jul 23 19:02:44 EDT 2013


On 7/23/2013 5:52 PM, steve at divillo.com wrote:
> I think that itertools may be able to do what I want but I have not
> been able to figure out how.

A recursive generator suffices.
> I want to convert an arbitrary number of lists with an arbitrary
> number of elements in each list into a single list as follows.
>> Say I have three lists:
>> [[A0,A1,A2], [B0,B1,B2] [C0,C1,C2]]
>> I would like to convert those to a single list that looks like this:
>> [A0,B0,C0,C1,C2,B1,C0,C1,C2,B2,C0,C1,C2,
 > A1,B0,C0,C1,C2,B1,C0,C1,C2,B2,C0,C1,C2,
 > A2,B0,C0,C1,C2,B1,C0,C1,C2,B2,C0,C1,C2]
def crossflat(lofl):
 if lofl:
 first = lofl.pop(0)
 for o in first:
 yield o
 yield from crossflat(lofl.copy())
A0, A1, A2 = 100, 101, 102
B0, B1, B2 = 10, 11, 12
C0, C1, C2 = 0, 1, 2
LL = [[A0, A1, A2], [B0, B1, B2], [C0, C1, C2]]
cfLL = list(crossflat(LL))
print(cfLL)
assert cfLL == [
 A0, B0, C0, C1, C2, B1, C0, C1, C2, B2, C0, C1, C2,
 A1, B0, C0, C1, C2, B1, C0, C1, C2, B2, C0, C1, C2,
 A2, B0, C0, C1, C2, B1, C0, C1, C2, B2, C0, C1, C2]
passes
-- 
Terry Jan Reedy


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /