Re: [問題] list

看板Python作者 (因為失去所以想念)時間15年前 (2009/12/06 19:44), 編輯推噓2(204)
留言6則, 2人參與, 最新討論串2/2 (看更多)
在我看來你是想要達到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

12/06 23:19, , 1F
謝謝,我最後還是用了try/except
12/06 23:19, 1F

12/07 16:49, , 2F
如果用dict可以參考一下這樣寫...
12/07 16:49, 2F

12/07 16:49, , 3F
def my_problem(a):
12/07 16:49, 3F

12/07 16:50, , 4F
return {1: 'one', 2: 'two', 3: 'three'}\
12/07 16:50, 4F

12/07 16:51, , 5F
.get(a, 'larger than three')
12/07 16:51, 5F

12/07 16:52, , 6F
以上的寫法 輸入非1,2,3的值都會回傳'larger than three'
12/07 16:52, 6F
文章代碼(AID): #1B6vakOs (Python)
討論串 (同標題文章)
本文引述了以下文章的的內容:
3
6
15年前, 12/06
完整討論串 (本文為第 2 之 2 篇):
2
6
3
6
15年前, 12/06
文章代碼(AID): #1B6vakOs (Python)