我有一个变量 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
if s in ('a', 'b'):
return 1
elif s in ('c', 'd'):
return 2
else:
return 3
d = {'a':1, 'b':1, 'c':2, 'd':2}
return d.get(s, 3)
如果只返回固定值,字典可能是最好的方法。
if s in 'ab':
return 1
elif s in 'cd':
return 2
else:
return 3
return 1 if (x in 'ab') else 2 if (x in 'cd') else 3
也许使用 if else 进行更多自我记录:
d = {'a':1, 'b':1, 'c':2, 'd':2} ## good choice is to replace case with dict when possible
return d[s] if s in d else 3
还可以使用 if else 来实现流行的第一个答案:
return (1 if s in ('a', 'b') else (2 if s in ('c','d') else 3))
简短简单:
return s in ('a', 'b')