简体   繁体   中英

How to check if all elements in a tuple or list are in another?

For example, I want to check every elements in tuple (1, 2) are in tuple (1, 2, 3, 4, 5) . I don't think use loop is a good way to do it, I think it could be done in one line.

You can use set.issubset or set.issuperset to check if every element in one tuple or list is in other.

>>> tuple1 = (1, 2)
>>> tuple2 = (1, 2, 3, 4, 5)
>>> set(tuple1).issubset(tuple2)
True
>>> set(tuple2).issuperset(tuple1)
True

I think you want this: ( Use all )

>>> all(i in (1,2,3,4,5) for i in (1,2))
True 

Since your question is specifically targeted at tuples/lists and not sets, I would assume you include cases where elements are repeated and the number of repetition matters. For example (1, 1, 3) is in (0, 1, 1, 2, 3) , but (1, 1, 3, 3) is not.

In this case, I claim that you would often be interested in the remainder of subtracting the smaller tuple/list from the larger tuple/list. Let's therefore first define a function remainder .

def remainder(l1, l2):
    # create a copy of l1
    l1_copy = list(l1)
    
    # remove from the copy all elements of l2
    for e in l2:
        l1_copy.remove(e)
        
    return tuple(l1_copy)

# remainder((1, 1, 3), (0, 1, 1, 2, 3)) returns (0, 2)
# remainder((1, 1, 3, 3), (0, 1, 1, 2, 3)) raises a ValueError

Now, we can define a function contains

def contains(l1, l2):
    try:
        remainder(l1, l2)
        return True
    except ValueError:
        return False

# contains((1, 1, 3), (0, 1, 1, 2, 3)) returns True
# contains((1, 1, 3, 3), (0, 1, 1, 2, 3)) returns False

Another alternative would be to create a simple function when the set doesn't come to mind.

def tuple_containment(a,b):
    ans = True
    for i in iter(b):
        ans &= i in a
    return ans

Now simply test them

>>> tuple_containment ((1,2,3,4,5), (1,2))
True
>>> tuple_containment ((1,2,3,4,5), (2,6))
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM