python中没有swith语句,只能使用if...elif...else..完成同样的工作,但是不必苦恼,因为可以使用字典:
python简明教程有很好的例子。
#!/usr/bin/python
# Filename: using_dict.py
# 'ab' is short for 'a'ddress'b'ookab = {
'Swaroop'
:
'swaroopch@byteofpython.info'
,
'Larry'
:
'larry@wall.org'
,
'Matsumoto'
:
'matz@ruby-lang.org'
,
'Spammer'
:
'spammer@hotmail.com'
}
"Swaroop's address is %s"
% ab[
'Swaroop'
]
# Adding a key/value pair
ab[
'Guido'
] =
'guido@python.org'
# Deleting a key/value pair
del
ab[
'Spammer'
]
'\nThere are %d contacts in the address-book\n'
%
len
(ab)
for
name, address
in
ab.items():
'Contact %s at %s'
% (name, address)
if
'Guido'
in
ab:
# OR ab.has_key('Guido')
"\nGuido's address is %s"
% ab[
'Guido'
]
所以延伸出了,字典的妙用,不止在python中,其他语言中也可适当使用字典。