有没有办法将两个"in"语句写成一个?



n = [5, 3, 17]
if 5 in n and 17 in n:
print("YES")

这样的东西似乎不起作用

if (5 and 17) in n:
print("YES")

有什么建议吗?

我认为Python中没有这样的东西。我能想到的最接近的是,set操作,例如。set.issubset:

>>> n = [5, 3, 17]
>>> ({5, 17}).issubset(n)
True

您可以使用这样的代码:

n = [5,3,7]
if all(item in n for item in [5,7]):
print("YES")
n = [5, 3, 17]
if set(n) & set((5, 7)):  # Using & which is intersect operator for two sets
print("YES")

另一种说法:

n = [5,3,17]
search = [5,17]
found = [x for x in search if x in n]
print("Count", len(found))
print("Matched", found)

最新更新