Speaking of list-comprehension?
Chinook
chinook.nr at tds.net
Thu Jun 30 23:13:13 EDT 2005
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]
>>>
>>> [tai - 10 | tai + 10 for tai in ta if tai >= 10]
[29, 29]
>>> [tai - 10 | tai + 10 for tai in ta]
[29, -1, -4, -2, 29]
>>> [tai - 10 or tai + 10 for tai in ta]
[5, -5, -8, -10, 9]
>>>
More information about the Python-list
mailing list