python - 测试一个值是否在两个列表之一中

标签 python

我的代码中有一个区域检查一个列表的项目是否在其他两个列表中,并根据此返回结果。

显然,第一个 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_onelist_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/

相关文章:

python - 通过路径导入 python 模块

python数据类 `__init_subclass__`不加载子类中的字段

python - 重启redis需要很长时间

android - Kivy--Plyer--Android--app未运行时发送通知

python - Pandas read_csv() 对我不起作用

python - 是否可以使用自定义方法/属性覆盖外键关系

python - 根据每个元组内的值对元组列表进行分区

python - Django django.db.utils.ProgrammingError。关系 <<Pages_account>> 不存在

python - 在 sklearn.metrics.plot_confusion_matrix 中抑制科学记数法

python - 用 replace() 替换的字符变为 0