作者cocokelly (因為失去所以想念)
看板Python
標題Re: [問題] list
時間Sun Dec 6 19:44:43 2009
在我看來你是想要達到switch的功能??
一般Python若要達到switch會用Dict來達到..
好比說...
r_value = {
'1': 'one',
'2': 'two',
'3': 'three'
}[a]
這樣是你想要的嗎?若回到主題.. 你直接用ListA[a]不就好了?反正你a也是一個
index value, 不是嗎?
※ 引述《ilvicco (家齊說我是螞蟻)》之銘言:
: def my_problem4_1(a):
: if a==1:
: return "one"
: elif a==2:
: return "two"
: elif a==3:
: return "three"
: else:
: return "larger than three"
: Q: 不要用 if-else statement, 改用 list 來達到相同的功能
: 我:
: def my_problem4_1(a):
: listA=['one','two','three','larger than three']
: if a>4:
: print listA[3]
: else:
: print listA[a-1]
: 可是這樣還是用到 if-else 怎麼樣可以直接用list達到相同功能
:
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 122.116.222.205
推 ilvicco:謝謝,我最後還是用了try/except 12/06 23:19
推 SMUGEN:如果用dict可以參考一下這樣寫... 12/07 16:49
→ SMUGEN:def my_problem(a): 12/07 16:49
→ SMUGEN: return {1: 'one', 2: 'two', 3: 'three'}\ 12/07 16:50
→ SMUGEN: .get(a, 'larger than three') 12/07 16:51
→ SMUGEN:以上的寫法 輸入非1,2,3的值都會回傳'larger than three' 12/07 16:52