我有一个变量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
答案 0 :(得分:37)
if s in ('a', 'b'):
return 1
elif s in ('c', 'd'):
return 2
else:
return 3
答案 1 :(得分:12)
d = {'a':1, 'b':1, 'c':2, 'd':2}
return d.get(s, 3)
答案 2 :(得分:1)
如果只返回固定值,字典可能是最好的方法。
答案 3 :(得分:1)
if s in 'ab':
return 1
elif s in 'cd':
return 2
else:
return 3
答案 4 :(得分:1)
使用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))
答案 5 :(得分:1)
return 1 if (x in 'ab') else 2 if (x in 'cd') else 3