If all in list == something

前端 未结 4 1485
遇见更好的自我
遇见更好的自我 2020-12-15 04:10

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         


        
相关标签:
4条回答
  • 2020-12-15 04:22

    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.

    0 讨论(0)
  • 2020-12-15 04:23

    Do you mean

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

    ?

    Edit: Changed to is. Slightly faster.

    0 讨论(0)
  • 2020-12-15 04:31

    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.

    0 讨论(0)
  • 2020-12-15 04:31

    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

    0 讨论(0)
提交回复
热议问题