我有一个变量s,其中包含一个单字母字符串
s = 'a'
根据该变量的值,我想返回不同的内容。到目前为止,我正在按照以下方式进行:
if s == 'a' or s == 'b':
return 1
elif s == 'c' or s == 'd':
return 2
else:
return 3
有更好的写法吗?更Pythonic的方法?还是这个最高效?
之前我错误地像这样写:
if s == 'a' or 'b':
...
显然那行代码行不通,而我这么写相当愚蠢。我知道条件赋值,并尝试过这个方法:
return 1 if s == 'a' or s == 'b' ...
我想我的问题具体来说是,有没有一种方法可以比较一个变量和两个值,而不必输入 something == something or something == something
getopt
模块。 - Jesse Dhillon