看板 Python 關於我們 聯絡資訊
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: 114.44.123.182
wxyy:listA[(a < 4 and [a-1] or [3])[0]] 這樣算不算 ? 12/06 19:13
Johan:try / except ? 12/06 19:17
wxyy:喔 還有一個 listA[min(a, 3)] 12/06 19:18
wxyy:上面打錯了 應該是 listA[min(4, a) - 1] 12/06 19:20
ilvicco:wxyy 意思是怎麼寫= =? Johan我不會try except 的寫法.. 12/06 19:38
sbrhsieh:先了解 min function 的用途,應該就會懂 wxyy 的意思 12/06 19:47