作者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
1F:推 ilvicco:谢谢,我最後还是用了try/except 12/06 23:19
2F:推 SMUGEN:如果用dict可以参考一下这样写... 12/07 16:49
3F:→ SMUGEN:def my_problem(a): 12/07 16:49
4F:→ SMUGEN: return {1: 'one', 2: 'two', 3: 'three'}\ 12/07 16:50
5F:→ SMUGEN: .get(a, 'larger than three') 12/07 16:51
6F:→ SMUGEN:以上的写法 输入非1,2,3的值都会回传'larger than three' 12/07 16:52