慕尼黑8549860
2019-09-03 19:28:17
我有一個(gè)變量s,其中包含一個(gè)字母的字符串s = 'a'根據(jù)該變量的值,我想返回不同的東西。到目前為止,我正在做一些事情:if s == 'a' or s == 'b': return 1elif s == 'c' or s == 'd': return 2else: return 3有沒有更好的方法來寫這個(gè)?一個(gè)更Pythonic的方式?或者這是最有效的?以前,我錯(cuò)誤地有這樣的事情:if s == 'a' or 'b': ...顯然這不起作用,對我來說相當(dāng)愚蠢。我知道條件賦值并試過這個(gè):return 1 if s == 'a' or s == 'b' ...我想我的問題是專門有一種方法可以將變量與兩個(gè)值進(jìn)行比較,而無需鍵入 something == something or something == something
4 回答

qq_遁去的一_1
TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
if s in ('a', 'b'):
return 1
elif s in ('c', 'd'):
return 2
else:
return 3

慕的地10843
TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
也許更多的自我記錄使用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實(shí)現(xiàn)流行的第一個(gè)答案:
return (1 if s in ('a', 'b') else (2 if s in ('c','d') else 3))
添加回答
舉報(bào)
0/150
提交
取消