【发布时间】:2021-11-07 14:37:45
【问题描述】:
有没有短版的
n = [5, 3, 17]
if 5 in n and 17 in n:
print("YES")
类似的东西似乎不起作用
if (5 and 17) in n:
print("YES")
有什么建议吗?
【问题讨论】:
标签: python python-3.x logic
有没有短版的
n = [5, 3, 17]
if 5 in n and 17 in n:
print("YES")
类似的东西似乎不起作用
if (5 and 17) in n:
print("YES")
有什么建议吗?
【问题讨论】:
标签: python python-3.x logic
我认为 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)
【讨论】: