Learning Python 10.22
Python中没有switch,只有if...elif...else,需要时可以考虑用dict配合lambda(dict中的value存放lambda表达式,lambda相关会在后面详述)。
关于True和False(仅限于Python3.2.3,估计后面会修改):1==True为True,0==False为True,其余所有数字==True与==False均为False。True/False与数字的&、|操作返回的结果是数字(不会有“短路”现象),但True/False与数字的and、or操作返回的结果取决于“短路”现象基础上最后一个操作数的类型(与C语言将除0以外的所有数均视为True不同,而且似乎在and和&的统一上没做好,真是太神奇了,又想起关于Javascript的"wat"了,这本书啃完之后就去啃"Javascript权威指南",唉没活干真是凄惨)
1 print(2==True, 2==False) 2 #False False 3 print(True&2, 2&True, True and 2, 2 and True, False and 2, 0 and True) 4 #0 0 2 True False 0 5 print(True|2, 2|True, True or 2, 2 or True, False or 2, 0 or True) 6 #3 3 True 2 2 True
关于 y if x else z的两种替代方法(在x为bool型时可用):
1 def f(b): 2 x = b if b>0 else -2*b 3 y = (b>0 and b) or -2*b 4 z = [-2*b, b][b>0] 5 print(x, y, z) 6 f(9) 7 #9 9 9 8 f(-9) 9 #18 18 18
关于循环语法Python的特点有两个:一是while循环的else用于正常跳出循环,二是for ... in ...,并且http://www.cnblogs.com/kilimanjaroup/archive/2012/10/23/2734326.html中提过的multiple-target assignements可直接用于其中,如
1 for (a, *b, c) in [(1, 2, 3, 4), (5, 6, 7, 8)]: 2 print(a, b, c) 3 #1 [2, 3] 4 4 #5 [6, 7] 8
for循环里可能用到range()、zip()、enumerate(),后两者用法如下:
1 L1 = [1,2,3,4] 2 L2 = [5,6,7,8] 3 for (x,y) in zip(L1, L2): 4 print(x,y) 5 #1 5 6 #2 6 7 #3 7 8 #4 8 9 s = "Hello" 10 for (offset, item) in enumerate(s): 11 print(offset, item)4 8 12 #0 H 13 #1 e 14 #2 l 15 #3 l 16 #4 o
403页止
浙公网安备 33010602011771号