我的代码中有一个区域可以检查一个列表中的项是否在其他两个列表中,并根据该结果返回结果。
显然,第一个IF子句始终为true,并且仅返回该子句的结果。
这里是示例:
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')
答案 0 :(得分:10)
(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
不在这些列表中。
答案 1 :(得分:3)
将第一个if
更改为
if day not in list_one + list_two
当前,您没有元素列表,只有两个列表的元组。因此,要成为in
,该元素必须是这些列表之一。
答案 2 :(得分:1)
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 and day not in list_two):
print('Case one')
elif day in list_one:
print('Case two')
elif day in list_two:
print('Case three')
答案 3 :(得分:1)
由于您已经有两个if
块来测试day
是否在任一列表中,因此出于您的目的,简单地使用else
块来进行检查就更容易(更有效) day
不在两个列表中:
if day in list_one:
print('Case two')
elif day in list_two:
print('Case three')
else:
print('Case one')
答案 4 :(得分:0)
或者any
,要检查是否有任何元素为真,请遍历两个列表[list_one,list_two]
(如果其中之一为真),因为使用in
会声明一个布尔语句:
...
if any(day in i for i in [list_one,list_two]):
...
...