list comprehension question
Bengt Richter
bokr at oz.net
Mon Mar 25 14:10:33 EST 2002
On Mon, 25 Mar 2002 00:25:15 -0500, Tim Peters <tim.one at comcast.net> wrote:
>[Tripp Scott]
>> thanks for the tip. actually, the essence of what i wanted to
>> ask was: "can that SOMETHING be a list of more than one elements
>> which will be _flatly_ added to the result list."
>
>No. len([f(x) for x in y]) == len(y) whenever no exception occurs,
>regardless of the form of f() or type of y.
>
>> as another example, can i generate this list
>>
>> [1,1 2,2,2, 3,3,3,3, 4,4]
>>
>> with a list comprehension that contains one 'for' clause?
>
>Sure, via the obvious spelling:
>
> [i for i in 1,1, 2,2,2, 3,3,3,3, 4,4]
>
>Cleverness can't improve one that.
Nope. Simple is best, but you _can_ also mess with 'for x in ...'
>>> [x<2 and 1 or x<5 and 2 or x<9 and 3 or x<=11 and 4 for x in xrange(11)]
[1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4]
which also has one 'for' clause ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list