defspread(arg):
ret =[]for i in arg:ifisinstance(i,list):
ret.extend(i)else:
ret.append(i)return ret
defdeep_flatten(lst):
result =[]
result.extend(
spread(list(map(lambda x: deep_flatten(x)iftype(x)==listelse x, lst))))return result
deep_flatten([1,[2],[[3],4],5])# [1,2,3,4,5]
defdifference_by(a, b, fn):
b =set(map(fn, b))return[item for item in a if fn(item)notin b]from math import floor
difference_by([2.1,1.2],[2.3,3.4],floor)# [1.2]
difference_by([{'x':2},{'x':1}],[{'x':1}],lambda v : v['x'])# [ { x: 2 } ]
17.链式函数调用
你可以在一行代码内调用多个函数。
defadd(a, b):return a + b
defsubtract(a, b):return a - b
a, b =4,5print((subtract if a > b else add)(a, b))# 9
18.检查重复项
如下代码将检查两个列表是不是有重复项。
defhas_duplicates(lst):returnlen(lst)!=len(set(lst))
x =[1,2,3,4,5,5]
y =[1,2,3,4,5]
has_duplicates(x)# True
has_duplicates(y)# False
19.合并两个字典
下面的方法将用于合并两个字典。
defmerge_two_dicts(a, b):
c = a.copy()# make a copy of a
c.update(b)# modify keys and values of a with the ones from b return c
a ={'x':1,'y':2}
b ={'y':3,'z':4}print(merge_two_dicts(a, b))# {'y': 3, 'x': 1, 'z': 4}
在 Python 3.5 或更高版本中,我们也可以用以下方式合并字典:
defmerge_dictionaries(a, b)return{**a,**b}
a ={'x':1,'y':2}
b ={'y':3,'z':4}print(merge_dictionaries(a, b))# {'y': 3, 'x': 1, 'z': 4}
import time
start_time = time.time()
a =1
b =2
c = a + b
print(c)#3
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)# ('Time: ', 1.1205673217773438e-05)
from copy import deepcopy
from random import randint
defshuffle(lst):
temp_lst = deepcopy(lst)
m =len(temp_lst)while(m):
m -=1
i = randint(0, m)
temp_lst[m], temp_lst[i]= temp_lst[i], temp_lst[m]return temp_lst
foo =[1,2,3]
shuffle(foo)# [2,3,1] , foo = [1,2,3]
28.展开列表
将列表内的所有元素,包括子列表,都展开成一个列表。
defspread(arg):
ret =[]for i in arg:ifisinstance(i,list):
ret.extend(i)else:
ret.append(i)return ret
spread([1,2,3,[4,5,6],[7],8,9])# [1,2,3,4,5,6,7,8,9]
29.交换值
不需要额外的操作就能交换两个变量的值。
defswap(a, b):return b, a
a, b =-1,14
swap(a, b)# (14, -1)
spread([1,2,3,[4,5,6],[7],8,9])# [1,2,3,4,5,6,7,8,9]
30.字典默认值
通过 Key 取对应的 Value 值,可以通过以下方式设置默认值。如果 get() 方法没有设置默认值,那么如果遇到不存在的 Key,则会返回 None。