Re: Conditional iteration
- From: at <at@xxxxxxx>
- Date: Thu, 14 Dec 2006 19:03:16 +0100
Dear Duncan,
Points taken. Its just a workaround for a specific case, I know. Maybe I
just love the elegance of
new_list = [x for x in some_list if some_cond]
and like to see it extended...
I got I nice tip on generators however which would allow me to something
similar without consuming too much additional resources.
Kind regards,
Arjan
Duncan Booth wrote:
at <at@xxxxxxx> wrote:
By the way,
I think by approving
a = b if condition else c
used to avloind
if condition:
a = b
else:
a = c
Neither of those is much of an improvement over the other, and in fact if
b or c are complex expressions I would definitely favour the longhand
form. The benefit of having a conditional expression though is that in
some situations it can make the code clearer by allowing you to avoid
creating a name at all. e.g. if 'a' was then used as a parameter in a
function call:
d = fn(b if condition else c)
and a has disappeared entirely.
which is dealing with same psychological problem, Guido also
recognizes some need...
Is it redundant according to your criteria, yes I would say:
a = {True: a, False: c}[condition]
or
a = [c, a][condition]
would yield exactly the same even in one sentence....
You do realise, I hope, that neither of these last two gives the same
results as the inline 'if'?
-1x = 0
print 3/x if x != 0 else -1
print {True: 3/x, False: -1}[x != 0]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print {True: 3/x, False: -1}[x != 0]
ZeroDivisionError: integer division or modulo by zero
print [-1, 3/x][x != 0]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print [-1, 3/x][x != 0]
ZeroDivisionError: integer division or modulo by zero
and before you suggest the good old standby and/or technique, that fails
for other values:
-1print x != 0 and 3/x or -1
-1x=5
print x != 0 and 3/x or -1
You need to use the messy:
0print (x != 0 and (3/x,) or (-1,))[0]
to get exactly the same effect as the inline if with loss of both
readability and performance.
.
- References:
- Conditional iteration
- From: at
- Re: Conditional iteration
- From: Paul Rubin
- Re: Conditional iteration
- From: at
- Re: Conditional iteration
- From: Carl Banks
- Re: Conditional iteration
- From: at
- Re: Conditional iteration
- From: Carl Banks
- Re: Conditional iteration
- From: at
- Re: Conditional iteration
- From: at
- Re: Conditional iteration
- From: Duncan Booth
- Conditional iteration
- Prev by Date: Re: tuple.index()
- Next by Date: Re: Conditional iteration
- Previous by thread: Re: Conditional iteration
- Next by thread: Re: Conditional iteration
- Index(es):
Relevant Pages
|
|