开发者

How to do "if-for" statement in python?

With python, I would like to run a test over an entire list, and, if all 开发者_如何学Pythonthe statements are true for each item in the list, take a certain action.

Pseudo-code: If "test involving x" is true for every x in "list", then do "this".

It seems like there should be a simple way to do this.

What syntax should I use in python?


Use all(). It takes an iterable as an argument and return True if all entries evaluate to True. Example:

if all((3, True, "abc")):
    print "Yes!"

You will probably need some kind of generator expression, like

if all(x > 3 for x in lst):
    do_stuff()


>>> x = [True, False, True, False]
>>> all(x)
False

all() returns True if all the elements in the list are True

Similarly, any() will return True if any element is true.


Example (test all elements are greater than 0)

if all(x > 0 for x in list_of_xs):
    do_something()

Above originally used a list comprehension (if all([x > 0 for x in list_of_xs]): ) which as pointed out by delnan (Thanks) a generator expression would be faster as the generator expression terminates at the first False, while this expression applies the comparison to all elements of the list.

However, be careful with generator expression like:

all(x > 0 for x in list_of_xs)

If you are using pylab (launch ipython as 'ipython -pylab'), the all function is replaced with numpy.all which doesn't process generator expressions properly.

all([x>0 for x in [3,-1,5]]) ## False
numpy.all([x>0 for x in [3,-1,5]]) ## False
all(x>0 for x in [3,-1,5]) ## False
numpy.all(x>0 for x in [3,-1,5]) ## True 


I believe you want the all() method:

$ python
>>> help(all)
Help on built-in function all in module __builtin__:

all(...)
    all(iterable) -> bool

    Return True if bool(x) is True for all values x in the iterable.


if reduce(lambda x, y: x and involve(y), yourlist, True):
   certain_action()

involve is the action you want to involve for each element in the list, yourlist is your original list, certain_action is the action you want to perform if all the statements are true.


all() alone doesn't work well if you need an extra map() phase.

see below:

all((x==0 for x in xrange(1000))

and:

all([x==0 for x in xrange(1000)])

the 2nd example will perform 1000 compare even the 2nd compare render the whole result false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜