if statement - Python: loop in elif condition -
i'm running python 3.
is possible put loop in condition elif? here's basic idea i'm trying achieve. number of items in list not constant.
if some_condition: elif [ x.method() x in list ]: x else: else now, comes mind:
if some_condition: x in list: if x.method(): x break but i'm trying avoid running if statements, there's lot of stuff going on in them. , in elif part , not in else.
edit / more clarification:
it seems need any( x.method() x in list ) reference x can use x if condition true.
here's whole concept i'm trying again:
if condition: elif list[0].method(): list[0] elif list[1].method(): list[1] ... elif list[n].method(): list[n] else: where method() method returns true or false, , n size of list , not constant.
i don't think want -- have entirely in elif -- possible. you'd have evaluate whether there any such value in list, , bind x in condition. far know, not possible in python's syntax. you can not assignment in condition, , while loop variable in list comprehension can "leak" outside scope, same not true generator.
>>> if any(x x in range(10) if x >= 5): ... print x nameerror: name 'x' not defined >>> if any([x x in range(10) if x >= 5]): ... print x 9 in second case (list), have reference x, last value entire list, , in first case (generator), x can not resolved @ all.
instead, here's variant, using generator expression combine for if, , adding else for enumate final else clause.
if some_condition: print "do this" else: x in (x x in lst if foo(x)): print "do to", x break else: print "do else"
Comments
Post a Comment