-----Original Message-----
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of John Fouhy
Sent: Monday, February 26, 2007 4:00 PM
To: Smith, Jeff
Cc: tutor@python.org
Subject: Re: [Tutor] Another list comprehension question

On 27/02/07, Smith, Jeff <[EMAIL PROTECTED]> 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'] }

This was a mockup from a much larger code fragment where the
get_clists() and get_clist() functions are part of an API to a CMS
system which return lists constructed from calls into the CMS system.


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



>This will do it:
>
>Or [x for k in get_clists() for x in get_clist(k)] using your original
structure.

I realize however that this is probably much less efficient since you
are iterating over the inner list rather than just taking it on in
whole.

Thanks!
Jeff
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to