Python如果a = this或this或this

Bri*_*ian 1 python

如果我有一个功能:

if a_string == "a" or a_string == "b" or a_string == "c":
    # do this
Run Code Online (Sandbox Code Playgroud)

如果没有重复或陈述,我怎么能以不同的方式写出来?或者这是最好的方式?

sen*_*hin 9

if a_string in ["a", "b", "c"]:
    # do stuff
Run Code Online (Sandbox Code Playgroud)

确保你==在条件中使用,而不是=,否则Python会抛出错误

编辑:正如Nigel Tufnel在他的回答中指出的那样,你也可以检查a的成员身份set,例如{'a', 'b', 'c'}.我相信这实际上通常更快,但如果你在列表/集合中只有三件事情,实际上并不重要.


Nig*_*nel 5

您可以测试列表成员身份:

if a_string in ["a", "b", "c"]:
    # do your thing
Run Code Online (Sandbox Code Playgroud)

或者您可以测试一组会员资格:

if a_string in {"a", "b", "c"}:
    # do your thing
Run Code Online (Sandbox Code Playgroud)

或者您可以测试元组成员资格:

if a_string in ("a", "b", "c"):
    # do your thing
Run Code Online (Sandbox Code Playgroud)

我认为list方式是最pythonic的方式,set方式是最正确的方式,tuple方式是最古怪的方式.

编辑:正如DSM和iCodez指出我错了:tuple方式是最快的(可能不是,参见编辑#2)和最pythonic的方式.活到老,学到老!

编辑#2:我知道microbenchmarking是Adolf Hitler以来最邪恶的东西,但无论如何我都会发布它:

python -O -m timeit '"c" in ("a", "b", "c")'
10000000 loops, best of 3: 0.0709 usec per loop

python -O -m timeit '"c" in ["a", "b", "c"]'
10000000 loops, best of 3: 0.0703 usec per loop

python -O -m timeit '"c" in {"a", "b", "c"}'
10000000 loops, best of 3: 0.184 usec per loop
Run Code Online (Sandbox Code Playgroud)

我不会解释timeit结果,但set时间是相当奇特的(可能是因为,呃,我不会解释结果).