如果元组中只有一项,元组上的运算符“in”似乎不仅会匹配整个字符串。该行为与“列表”和“设置”不同。 我不明白差异从何而来,是设计使然,有一些特定的用法还是一个错误?
Python 3.12.3 (tags/v3.12.3:f6650f9, Apr 9 2024, 14:05:25) [MSC v.1938 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> skip_funcs = ("ENG_EN1") # mis-match in tuple
>>> "ENG" in skip_funcs
True
>>> skip_funcs = ("ENG_EN1", "abc") # correct if the tuple has more than one component
>>> "ENG" in skip_funcs
False
>>> "ENG_EN1" in skip_funcs
True
>>> skip_funcs = ["ENG_EN1"] # correct for 'list'
>>> "ENG" in skip_funcs
False
>>> "ENG_EN1" in skip_funcs
True
>>> skip_funcs = {"ENG_EN1"} # correct for 'set'
>>> "ENG" in skip_funcs
False
>>> "ENG_EN1" in skip_funcs
True
skip_funcs = ("ENG_EN1")
没有定义元组,但是:
skip_funcs = ("ENG_EN1",)
是的。
与数学一样,Python 中的括号也用于定义优先级运算。当你写(“ENG_EN1”)时,你要求Python首先评估括号内的内容,即“ENG_EN1”。在 python 中 (“ENG_EN1”) == “ENG_EN1”。
为了区分用于定义优先级的括号和用于定义元组的括号,需要使用逗号。
skip_funcs = ("ENG_EN1",)