If all in list == something

2020-02-09 06:32发布

问题:

Using Python 2.6, is there a way to check if all the items of a sequence equals a given value, in one statement?

[pseudocode]
my_sequence = (2,5,7,82,35)

if all the values in (type(i) for i in my_sequence) == int:
     do()

Instead of, say:

my_sequence = (2,5,7,82,35)
all_int = True
for i in my_sequence:
    if type(i) is not int:
        all_int = False
        break

if all_int:
    do()

回答1:

Use:

all( type(i) is int for i in lst )

Example:

In [1]: lst = range(10)
In [2]: all( type(i) is int for i in lst )
Out[2]: True
In [3]: lst.append('steve')
In [4]: all( type(i) is int for i in lst )
Out[4]: False

[Edit]. Made cleaner as per comments.



回答2:

Do you mean

all( type(i) is int for i in my_list )

?

Edit: Changed to is. Slightly faster.



回答3:

I would suggest:

if all(isinstance(i, int) for i in my_list):

all and any first appeared in 2006 with Python 2.5 (feature implemented by Raymond Hettinger).
If you're using an older version of Python, the links provide sample implementations.

I also suggest using isinstance since it will also catch subclasses of int.



回答4:

For the sake of completeness I thought I would add the fact that NumPy's 'all' is different from the built-in 'all'. If for example running Python through Python(x,y), NumPy is loaded automatically (and cannot be unloaded as far as I know), so when trying to run the above code it produces rather unexpected results:

>>> if (all(v == 0 for v in [0,1])):
...     print 'this should not happen'
... this should not happen

More information on this is in Stack Overflow question numpy all differing from builtin all. As a solution you can either surround the generator with brackets to produce a list:

>>> all( [v == 0 for v in [0,1]] )
False

Or call the built-in function explicitly:

>>> __builtins__.all(v == 0 for v in [0,1,'2'])
False

I found a way to stop Spyder from importing NumPy per default: Spyder default module import list