列表合并
哪个函数能实现下面的功能:
[['aa', 'bb'], ['cc', 'dd']] => ['aa', 'bb', 'cc', 'dd']
[解决办法]
>>> sum([['aa', 'bb'], ['cc', 'dd']] ,[])
['aa', 'bb', 'cc', 'dd']
In [35]: list_of_list = [[i]*1000 for i in range(1000)] # 测试用数组
In [36]: from functools import reduce
In [37]: def collect_all_1(list_of_list):
...: return sum(list_of_list, [])
In [38]: def extend_and_return(x, y):
...: x.extend(y)
...: return x
In [39]: def collect_all_2(list_of_list):
...: return reduce(extend_and_return, list_of_list, [])
In [40]: collect_all_1(list_of_list) == collect_all_2(list_of_list) # 两个结果一样
Out[40]: True
In [41]: %timeit print(len(collect_all_1(list_of_list)))
1000000
1000000
1000000
1000000
1 loops, best of 3: 2.37 s per loop
In [42]: %timeit len(collect_all_1(list_of_list)) # 测试collect_all_1的效率
1 loops, best of 3: 2.37 s per loop
In [43]: %timeit len(collect_all_2(list_of_list)) # 测试collect_all_2的效率
100 loops, best of 3: 4.39 ms per loop
差别的原因:sum(..)在每加一项时,都会重新构造一个数组。reduce版本的避免了这个问题。