P: a = 3 b = 1 1 <= b <= a < 10#True NP: b >= 1and b <= a and a < 10#True
真值测试
1 2 3 4 5 6 7 8 9 10
P: name = 'Tim' langs = ['AS3', 'Lua', 'C'] info = {'name': 'Tim', 'sex': 'Male', 'age':23 } if name and langs and info: print('All True!') #All True! NP: if name != ''andlen(langs) > 0and info != {}: print('All True!') #All True!
P: numList = [1,2,3,4,5] sum = sum(numList) #sum = 15 maxNum = max(numList) #maxNum = 5 minNum = min(numList) #minNum = 1 from operator import mul prod = reduce(mul, numList, 1) #prod = 120 默认值传1以防空列表报错 NP: sum = 0 maxNum = -float('inf') minNum = float('inf') prod = 1 for num in numList: if num > maxNum: maxNum = num if num < minNum: minNum = num sum += num prod *= num # sum = 15 maxNum = 5 minNum = 1 prod = 120
列表推导式
1 2 3 4 5 6 7 8 9
P: l = [x*x for x inrange(10) if x % 3 == 0] #l = [0, 9, 36, 81] NP: l = [] for x inrange(10): if x % 3 == 0: l.append(x*x) #l = [0, 9, 36, 81]
P: for x in xrange(1,5): if x == 5: print'find 5' break else: print'can not find 5!' #can not find 5! NP: find = False for x in xrange(1,5): if x == 5: find = True print'find 5' break ifnot find: print'can not find 5!' #can not find 5!
P: a = 3 b = 2if a > 2else1 #b = 2 NP: if a > 2: b = 2 else: b = 1 #b = 2
如果你具备C的编程经验,你就会寻找A ? B : C的替代品。你可能发现A and B or C看起来还不错,但是b = a > 1 and False or True会返回True,而实际意图应该返回False。 使用b = False if a > 1 else True则会正确返回False。
Enumerate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
P: array = [1, 2, 3, 4, 5] for i, e inenumerate(array,0): print i, e #0 1 #1 2 #2 3 #3 4 #4 5 NP: for i in xrange(len(array)): print i, array[i] #0 1 #1 2 #2 3 #3 4 #4 5