我的代码中有一个区域检查一个列表的项目是否在其他两个列表中,并根据此返回结果。
显然,第一个 IF 子句始终为真,并且只返回该子句的结果。
例子如下:
from datetime import date
days = [date(2018, 9, 10), date(2018, 9, 11), date(2018, 9, 12)]
list_one = [date(2018, 9, 13), date(2018, 9, 14), date(2018, 9, 15)]
list_two = [date(2018, 9, 8), date(2018, 9, 9), date(2018, 9, 10)]
for day in days:
if day not in(list_one, list_two):
print('Case one')
elif day in list_one:
print('Case two')
elif day in list_two:
print('Case three')
最佳答案
(list_one, list_two)
是恰好 两个 元素的元组,包含 list_one
和 list_two
。由于 day
永远不会等于列表,因此 day not in (list_one, list_two)
结果为 True。
您可以合并列表并编写
lists = list_one + list_two
if day not in lists:
...
或使用
if day not in list_one and day not in list_two:
...
或者,应用 De Morgan's laws :
if not (day in list_one or day in list_two):
...
表示 day
不在这两个列表中。
关于python - 测试一个值是否在两个列表之一中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52256445/