所以我有一个数字值列表,如 my_num = [1,2,2,3,4,5]
我想要的是一个代码,用于检查列表中是否有1,2和3。 我的想法是:
如果my_num中的1和2和3:
做点什么
但问题是如果1和3在列表中,即使没有2在那里,也会执行代码执行。
答案 0 :(得分:1)
试试这个:
nums = [1,2,3,4]
>>> if (1 in nums) and (2 in nums) and (3 in nums):
... print('ok')
...
ok
>>> if (1 in nums) and (2 in nums) and (9 in nums):
... print('ok')
...
>>>
答案 1 :(得分:1)
查看标准库函数any
和all
。你可以这样写:
if any(a in my_num for a in (1, 2, 3)):
# do something if one of the numbers is in the list
if all(a in my_num for a in (1, 2, 3)):
# do something if all of them are in the list
答案 2 :(得分:0)
if 1 and 2 and 3 in my_num:
没有按照您的想法执行操作:它测试if 1
True
,if 2
,True
,然后if 3 in my_num
< / p>
您必须单独测试每个条件:
if 1 and in my_num and 2 in my_num and 3 in my_num:
答案 3 :(得分:0)
如果列表长度很长:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_in = [2, 3, 4]
if len(set(_in)) == len(set(nums)&set(_in)):
print("ok")