这里提供的所有优秀答案都集中在原海报的具体要求上,并集中在
if 1 in {x,y,z}
由Martijn Pieters提出的解决方案。
他们忽略的是这个问题更广泛的含义:
如何针对多个值测试一个变量?
如果使用字符串,例如:
测试字符串“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']
>>> {x, y, z}
{'in the beginning', 'throttle it back', 'Wild things'}
>>>
>>> if "Wild" in str([x, y, z]): print (True)
...
True
>>> if "Wild" in str({x, y, z}): print (True)
...
True
但是,正如
@codeforester
,使用此方法将丢失单词边界,如:
>>> x=['Wild things', 'throttle it back', 'in the beginning']
>>> if "rot" in str(x): print(True)
...
True
三个字母
rot
在列表中确实存在组合,但不作为单个单词存在。测试“rot”将失败,但如果其中一个列表项是“rot in hell”,那也将失败。
结果是,如果使用此方法,请小心搜索条件,并注意它确实有此限制。