Check if list contains only item x

后端 未结 8 1128
长发绾君心
长发绾君心 2020-12-17 17:03

Say all of w, x, y, and z can be in list A. Is there a shortcut for checking that it contains only x--eg. without negating the other variables?

w, x, y, and z

相关标签:
8条回答
  • 2020-12-17 17:41

    Heres another way:

    >>> [x] * 4 == [x,w,z,y]
    

    of the many already stated.

    0 讨论(0)
  • 2020-12-17 17:42

    There are two interpretations to this question:

    First, is the value of x contained in [w,y,z]:

    >>> w,x,y,z=1,2,3,2
    >>> any(x == v for v in [w,y,z])
    True
    >>> w,x,y,z=1,2,3,4
    >>> any(x == v for v in [w,y,z])
    False
    

    Or it could mean that they represent the same object:

    >>> w,x,y,z=1,2,3,4
    >>> any(x is v for v in [w,y,z])
    False
    >>> w,x,y,z=1,2,3,x
    >>> any(x is v for v in [w,y,z])
    True
    
    0 讨论(0)
提交回复
热议问题