[Tutor] Another list comprehension question

John Fouhy john at fouhy.net
Mon Feb 26 21:59:55 CET 2007


Hi Jeff,

On 27/02/07, Smith, Jeff <jsmith at medplus.com> wrote:
> I'm probably missing something simple here but is there anyway to
> accomplish the following with a list comprehension?
>
> 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']

This would be better represented as a dictionary:

>>> clists = { 1:['a', 'b', 'c'],
...            2:['x', 'y', 'z'],
...            3:['p', 'q'] }

You may also be able to replace get_clists() with a call to
clists.keys() (or just simple iteration), depending on what you are
doing.

>>> for k in clists:
...  print clists[k]
...
['a', 'b', 'c']
['x', 'y', 'z']
['p', 'q']

> files = list()
> for clist in get_clists():
>     files += get_clist(clist)

Just a comment -- you could write this as
"files.extend(get_clist(clist))", which would be slightly more
efficient.

> 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.

This will do it:

>>> [x for k in clists for x in clists[k]]
['a', 'b', 'c', 'x', 'y', 'z', 'p', 'q']

Or [x for k in get_clists() for x in get_clist(k)] using your original
structure.

HTH!

-- 
John.


More information about the Tutor mailing list