[Tutor] Another list comprehension question

Bob Gailer bgailer at alum.rpi.edu
Mon Feb 26 21:52:53 CET 2007


Smith, Jeff wrote:
> I'm probably missing something simple here but is there anyway to
> accomplish the following with a list comprehension?
>   
Each element created by a comprehension corresponds to an element 
returned by the for (if) clause. So we have to find a way for the for 
clause to return successively 'a', 'b', 'c', 'x', 'y', 'z', 'p', 'q'. 
The only way I can see to do that is with a generator. Which I think is 
more work than necessary for your purposes.


> def get_clists():
>     return [1, 2, 3]
>
> def get_clist(num):
>     if num == 1:
>         return ['a', 'b', 'c']
>     if num == 2:
>         return ['x', 'y', 'z']
>     if num == 3:
>         return ['p', 'q']
>
> files = list()
>   
Or just files = []
> for clist in get_clists():
>     files += get_clist(clist)
>
> My first attempt was to try 
> [get_clist(c) for c in get_clists()]
>
> but this returns a list of lists rather than the flat list from the
> original.
>
> Any help is appreciate...just trying to be as Pythonesque as possible
> :-)
>
> Jeff
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454



More information about the Tutor mailing list