关于itertools.groupby()
itertools.groupby()就是将相邻的并且相同的键值划分为同一组,相似功能可以看https://docs.python.org/3/library/itertools.html?highlight=groupby#itertools.groupby写的groupby类
>>> list_a ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'D', 'A', 'A', 'B', 'B', 'B'] >>> for date, items in groupby(list_a): ... print('date: {}'.format(date)) ... for item in items: ... print(item, end=" ") ... print(" ==========") ... date: A A A A A ========== date: B B B B ========== date: C C C ========== date: D D ========== date: A A A ========== date: B B B B ==========
是不是发现上述例子还有可简化之处,毕竟A的分组要都归为一组(这是因为存在不相邻的A才出现的情况):
>>> list_a ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'D', 'A', 'A', 'B', 'B', 'B'] >>> list_a.sort(key=lambda list: list) # 经过lambda匿名函数排序后,将相邻的元素放在一起 >>> list_a ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'C', 'C', 'D'] >>> for date, items in groupby(list_a): ... print('date: {}'.format(date)) ... for item in items: ... print(item, end=" ") ... print(" ==========") ... date: A A A A A A A ========== date: B B B B B B B ========== date: C C C ========== date: D D ==========
除了使用lambda匿名函数之外,还可以使用operator.itemgetter()函数,效率比lambda更快一些,具体可以看《Python Cookbook》
关于itertools.compress(data, selectors)
根据传递进去的选择器进行判断是否保留数据
>>> list1 = [1, 4, 7, 2, 98, 3, 6, 2] >>> list_TF = [0,1,0,1,1,1,0,0] >>> list_TF = [n ==1 for n in list_TF] >>> list_TF [False, True, False, True, True, True, False, False] >>> from itertools import compress >>> list(compress(list1, list_TF)) [4, 2, 98, 3]
其实通过教程我们还可以发现compress是大致如下:
>>> list1 [1, 4, 7, 2, 98, 3, 6, 2] >>> list_TF [False, True, False, True, True, True, False, False] >>> [n for n,s in zip(list1, list_TF) if s] [4, 2, 98, 3]
如果觉得慢,还可以使用生成器来代替