python - 如果 L 中为 'a' 或 'b',其中 L 是一个列表 (Python)

标签 python

我在处理以下逻辑时遇到了问题:

假设我有一个列表 L = ['a', 'b', 'c']


两项都在列表中...

if ('a' or 'b') in L:
    print 'it\'s there!'
else:
    print 'No sorry'

打印它就在那里!


列表中只有第一项...

if ('a' or 'd') in L:
    print 'it\'s there!'
else:
    print 'No sorry'

打印它就在那里!


列表中的任何一项...

if ('e' or 'd') in L:
    print 'it\'s there!'
else:
    print 'No sorry'

打印No sorry


这是令人困惑的一个只有列表中的第二个项...

if ('e' or 'a') in L:
    print 'it\'s there!'
else:
    print 'No sorry'

打印No sorry


我不明白为什么这不是一个真实的陈述。这如何概括为具有 n 个条件的 or 语句?

在 3,2,1... 中拍额头的简单答案

最佳答案

让我们分解一下表达式:

('e' or 'a') 将首先检查 'e' 是否为 True。如果是,表达式将返回 'e'。如果不是,它将返回 'a'

由于所有非空字符串都返回 True,因此该表达式将始终返回 'e'。这意味着 if ('e' or 'a') in L: 可以转换为 if 'e' in L,在本例中为 False

检查列表是否至少包含一组值中的一个值的更通用方法是使用 any 函数和生成器表达式。

if any(c in L for c in ('a', 'e')):

关于python - 如果 L 中为 'a' 或 'b',其中 L 是一个列表 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21344842/

相关文章:

python - 将 python3 移动到 brew 并更新

python - Gunicorn 如何将请求转发给 Flask

python - pandas - 从 json 数据创建数据框,指定要包含哪些列

用于提取字段的 Python 一行代码

python - html 不发送帖子查看

python - Keras model.fit 上的 ValueError : setting an array element with a sequence.

python - 如何将嵌套列表转换为字典?

python - 如何找到两个日期之间的中位数月份?

python - DRF : ModelSerializer for nested JSON data

python - 在python中自动将所有相对导入转换为绝对导入