这里提供的所有优秀答案都集中在原帖的具体要求上,集中在Martijn Pieters提出的if 1 in {x,y,z}
解决方案上。
它们忽略了问题的更广泛含义:
如何测试一个变量与多个值的匹配情况?
提供的解决方案如果使用字符串,将无法对部分匹配进行检测,例如:
测试字符串“Wild”是否在多个值中。
>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in {x, y, z}: print (True)
...
或者
>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in [x, y, z]: print (True)
...
对于这种情况,将其转换为字符串是最简单的。
>>> [x, y, z]
['Wild things', 'throttle it back', 'in the beginning']
>>>
>>>
>>> if "Wild" in str([x, y, z]): print (True)
...
True
>>> if "Wild" in str(): print (True)
...
True
需要注意的是,正如@codeforester
所提到的,使用这种方法会丢失单词边界,例如:
>>> x=['Wild things', 'throttle it back', 'in the beginning']
>>> if "rot" in str(x): print(True)
...
True
在列表中,的确存在由3个字母rot
组合而成的单词,但是它们不会作为一个独立的单词出现。如果搜索" rot ",测试将失败,但如果其中一个列表项是"rot in hell",那么也会失败。
因此,如果使用这种方法,请注意搜索条件并知道它有这个限制。
1
。 - user9011445any
/all
函数。 例如:all([1, 2, 3, 4, False])
将返回 Falseall([True, 1, 2, 3])
将返回 Trueany([False, 0, 0, False])
将返回 Falseany([False, 0, True, False])
将返回 True - edddif x == 0 or 1:
这样做,当然类似于if x or y == 0:
,但对新手来说可能仍然有点困惑。考虑到 "为什么我的 'x == 0 or 1' 不起作用?" 这类问题的数量之多,我更愿意使用 这个问题 作为我们的标准重复目标。 - Aran-Fey0
、0.0
或False
等“假值”进行比较时要特别小心。你很容易写出错误的代码,从而得到“正确”的答案。 - smci