![](/img/trans.png)
[英]How to check if all elements of a tuple are elements of other tuple in python?
[英]How to check if all elements in a tuple or list are in another?
例如,我想檢查元組(1, 2)
中的每個元素是否在元組(1, 2, 3, 4, 5)
中。 我不認為使用循環是一種好方法,我認為它可以在一行中完成。
您可以使用set.issubset
或set.issuperset
來檢查一個元組或列表中的每個元素是否在其他元素中。
>>> tuple1 = (1, 2)
>>> tuple2 = (1, 2, 3, 4, 5)
>>> set(tuple1).issubset(tuple2)
True
>>> set(tuple2).issuperset(tuple1)
True
我想你想要這個:( 全部使用)
>>> all(i in (1,2,3,4,5) for i in (1,2))
True
由於您的問題專門針對元組/列表而不是集合,因此我假設您包括重復元素和重復次數很重要的情況。 例如(1, 1, 3)
在(0, 1, 1, 2, 3)
中,但(1, 1, 3, 3)
不在。
在這種情況下,我聲稱您通常會對從較大的元組/列表中減去較小的元組/列表的剩余部分感興趣。 因此,讓我們首先定義一個函數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
現在,我們可以定義一個函數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
另一種選擇是在不想到集合時創建一個簡單的函數。
def tuple_containment(a,b):
ans = True
for i in iter(b):
ans &= i in a
return ans
現在只需測試它們
>>> tuple_containment ((1,2,3,4,5), (1,2))
True
>>> tuple_containment ((1,2,3,4,5), (2,6))
False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.