python - 如果语句检查列表包含在不应该返回 true 时返回 true

标签 python list if-statement

我有一个包含值的列表:

['1', '3', '4', '4']

我有一个 if 语句,它会检查值是否包含在列表中,然后输出一个语句:

if "1" and "2" and "3" in columns:
    print "1, 2 and 3"

考虑到列表不包含值“2”,它不应该打印语句,但是它是:

输出:

1, 2 and 3

有人能解释一下为什么会这样吗?是不是 Python 读取列表的方式导致了这种情况发生?

最佳答案

它按照 operator precedence 的顺序进行评估:

if "1" and "2" and ("3" in columns):

展开为:

if "1" and "2" and True:

然后计算 ("1"and "2") 给我们留下:

if "2" and True

最后:

if True:

相反,您可以检查字符串的是否是的子集:

if {"1", "2", "3"}.issubset(columns):
    print "1, 2 and 3"

关于python - 如果语句检查列表包含在不应该返回 true 时返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31780687/

相关文章:

python - 基于日期时间的 Holoviews 颜色和颜色条

python - 是否有一个Python函数在循环内,在到达列表的最后一个索引后,它将再次转到第一个索引,然后循环重新启动?

java - 以编程方式区分 LinkedList 和 List

c++ - arduino:其他程序不工作

ios - NSError 域检查条件在 iOS 8 中失败

python - 通过其父项修改嵌套字典键名

r - 如何将列表中的特定对象展开.grid以形成新列表

python - 如何使用Python从Json文件的嵌套列表中提取对象?

angular - mat-cell Angular 8 中的 if else

python - 是否可以从 RetryError 中恢复 HTTP 响应? (Python请求库)