#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 10
#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]
列表推导嵌套
1 2 3 4 5 6 7 8 9 10 11 12
#P gen = (item for sl in nested_list if list_condition(sl) for item in sl if item_condition(item)) for item in gen: # do something...
#NP for sub_list in nested_list: if list_condition(sub_list): for item in sub_list: if item_condition(item): # do something...
循环嵌套
1 2 3 4 5 6 7 8 9 10
#P from itertools import product for x, y, z in product(x_list, y_list, z_list): # do something for x, y, z #NP for x in x_list: for y in y_list: for z in z_list: # do something for x & y
字典键值列表
1 2 3 4 5 6 7
#P for key in my_dict: # my_dict[key] ...
#NP for key in my_dict.keys(): # my_dict[key] ...
只有当循环中需要更改key值的情况下,我们需要使用 my_dict.keys()
字典键值判断
1 2 3 4 5 6 7
#P if key in my_dict: # ...do something with d[key]
#NP if my_dict.has_key(key): # ...do something with d[key]
字典 get 和 setdefault 方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#P navs = {} for (portfolio, equity, position) in data: # 使用 get 方法 navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity] # 或者使用 setdefault 方法 navs.setdefault(portfolio, 0) navs[portfolio] += position * prices[equity]
#NP navs = {} for (portfolio, equity, position) in data: if portfolio notin navs: navs[portfolio] = 0 navs[portfolio] += position * prices[equity]