有没有办法将两个 "in" 语句写在一个语句中?
Is there a way to write two "in" statements in one?
有没有短版
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]
search = [5,17]
found = [x for x in search if x in n]
print("Count", len(found))
print("Matched", found)
n = [5, 3, 17]
if set(n) & set((5, 7)): # Using & which is intersect operator for two sets
print("YES")
有没有短版
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]
search = [5,17]
found = [x for x in search if x in n]
print("Count", len(found))
print("Matched", found)
n = [5, 3, 17]
if set(n) & set((5, 7)): # Using & which is intersect operator for two sets
print("YES")