Check if list contains only item x

后端 未结 8 1127
长发绾君心
长发绾君心 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:21

    This checks that all elements in A are equal to x without reference to any other variables:

    all(element==x for element in A)
    
    0 讨论(0)
  • 2020-12-17 17:28
    A=[w,y,x,z]
    all(p == x for p in A)
    
    0 讨论(0)
  • 2020-12-17 17:30

    I'm not sure what without negating the other variables means, but I suspect that this is what you want:

    if all(item == x for item in myList): 
        #do stuff
    
    0 讨论(0)
  • 2020-12-17 17:36
    {x} == {w,x,y,z} & set(A)
    

    This will work if all of [w,x,y,z] and items in A are hashable.

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

    That, or if you don't want to deal with a loop:

    >>> a = [w,x,y,z]
    >>> a.count(x) == len(a) and a
    

    (and a is added to check against empty list)

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

    If all items in the list are hashable:

    set(A) == set([x])
    
    0 讨论(0)
提交回复
热议问题