Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #51107

Re: Converting a list of lists to a single list

Date 2013-07-23 23:52 +0100
From MRAB <python@mrabarnett.plus.com>
Subject Re: Converting a list of lists to a single list
References <ee6f5c48-6cb1-498f-813a-be2eef5411fc@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.5017.1374619944.3114.python-list@python.org> (permalink)

Show all headers | View raw


On 23/07/2013 22:52, steve@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.
>
> 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]
>
> An easier way to visualize the pattern I want is as a tree.
>
> 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
>
Using recursion:

def tree_list(items):
     if len(items) == 1:
         return items[0]

     sublist = tree_list(items[1 : ])

     result = []

     for item in items[0]:
         result.append(item)
         result.extend(sublist)

     return result

items = [["A0","A1","A2"], ["B0","B1","B2"], ["C0","C1","C2"]]
print(tree_list(items))

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Converting a list of lists to a single list steve@divillo.com - 2013-07-23 14:52 -0700
  Re: Converting a list of lists to a single list Rafael Durán Castañeda <rafadurancastaneda@gmail.com> - 2013-07-24 00:34 +0200
  Re: Converting a list of lists to a single list MRAB <python@mrabarnett.plus.com> - 2013-07-23 23:52 +0100
  Re: Converting a list of lists to a single list Zero Piraeus <schesis@gmail.com> - 2013-07-23 18:49 -0400
  Re: Converting a list of lists to a single list Terry Reedy <tjreedy@udel.edu> - 2013-07-23 19:02 -0400
  Re: Converting a list of lists to a single list Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-07-23 20:28 -0400
  Re: Converting a list of lists to a single list Chris Angelico <rosuav@gmail.com> - 2013-07-24 15:40 +1000
  Re: Converting a list of lists to a single list Terry Reedy <tjreedy@udel.edu> - 2013-07-24 11:56 -0400
  Re: Converting a list of lists to a single list steve@divillo.com - 2013-07-24 11:11 -0700

csiph-web