Speaking of list-comprehension?
George Sakkis
gsakkis at rutgers.edu
Fri Jul 1 01:06:58 EDT 2005
"Chinook" wrote:
> I'm probably just getting languages mixed up, but I thought in my Python
> readings over the last couple months that I had noticed an either/or
> expression (as opposed to a bitwise or, or truth test). Being a curious
> sort, I tried several variations of how a list comprehension *might* be
> constructed and got the results expected relative to the operators, but
> not the results I was trying to achieve.
>
> So, is it possible to achieve what the "for loop" (below) does in a
> single list comprehension? I don't even see a way to accomplish such in
> two list comprehensions with an intermediate result unless an index
> pattern was the criterion.
>
> Just wondering,
> Lee C
>
> PS I'm not suggesting it be added to the language :~) Beyond the new
> classes and decorators (simply a convienence), I'm for KISS even to the
> extent of the much abused Case statement.
>
> >>> ta = [5, 15, 12, 10, 9]
> >>> for i in range(len(ta)):
> ... if ta[i] >= 10:
> ... ta[i] -= 10
> ... else:
> ... ta[i] += 10
> ...
> >>> ta
> [15, 5, 2, 0, 19]
The following works, although its readability is debatable, to say the
least, let alone performance in the general worst case:
>>> ta = [5, 15, 12, 10, 9]
>>> ta = [(x+10,x-10)[x>=10] for x in ta]
>>> ta
> [15, 5, 2, 0, 19]
The lack of a ternary if?then:else operator manifests itself in such
examples, but alas, there isn't much hope that even python 3K will have
one...
Would-go-with-ugly-syntax-than-no-syntax-any-day'ly yrs,
George
More information about the Python-list
mailing list