乐趣区

itertools模块超实用方法

相信大家在学习 python 的过程中都用到过这个模块,但是可能只是用到了其中的一两个方法,对于其更强大的功能没有更深的认识。今天我就按照自己的方式向大家介绍一下这个模块。groupby: 用于分组
rows=[
{‘name’:’jim’,’date’:’07/01′},
{‘name’:’tom’,’date’:’07/01′},
{‘name’:’rose’,’date’:’07/01′},
{‘name’:’tom’,’date’:’07/02′},
{‘name’:’jim’,’date’:’07/03′},
{‘name’:’rose’,’date’:’07/02′},
]
#groupby 只能对连续数据进行分组,因此不能确定数据有序的情况下,建议进行排序操作
gbrows=sorted(rows,key=itemgetter[‘date’])

for gbdata,row in gbrows(gbrows,key=itemgetter[‘date’])
print(gbdata)
for i in row:
print(i)

# 以下是输出结果:
07/01/2018
{‘name’: ‘jim’, ‘date’: ’07/01/2018′}
{‘name’: ‘tom’, ‘date’: ’07/01/2018′}
{‘name’: ‘rose’, ‘date’: ’07/01/2018′}
07/02/2018
{‘name’: ‘tom’, ‘date’: ’07/02/2018′}
{‘name’: ‘rose’, ‘date’: ’07/02/2018′}
07/03/2018
{‘name’: ‘jim’, ‘date’: ’07/03/2018′}
permutations:按照给定位数对可迭代对象内元素进行组合
listed = [‘a’,’b’,’c’,’d’]

for i in permutations(listed,3):
print(i)

# 以下是输出结果 (由于结果比较多,我对格式进行了变化,但数据都是正确的)
(‘a’, ‘b’, ‘c’) (‘a’, ‘b’, ‘d’) (‘a’, ‘c’, ‘b’) (‘a’, ‘c’, ‘d’) (‘a’, ‘d’, ‘b’) (‘a’, ‘d’, ‘c’)
(‘b’, ‘a’, ‘c’) (‘b’, ‘a’, ‘d’) (‘b’, ‘c’, ‘a’) (‘b’, ‘c’, ‘d’) (‘b’, ‘d’, ‘a’)
(‘b’, ‘d’, ‘c’)
(‘c’, ‘a’, ‘b’) (‘c’, ‘a’, ‘d’) (‘c’, ‘b’, ‘a’) (‘c’, ‘b’, ‘d’) (‘c’, ‘d’, ‘a’) (‘c’, ‘d’, ‘b’)
(‘d’, ‘a’, ‘b’) (‘d’, ‘a’, ‘c’) (‘d’, ‘b’, ‘a’) (‘d’, ‘b’, ‘c’) (‘d’, ‘c’, ‘a’) (‘d’, ‘c’, ‘b’)
combinations:按照给定位数对可迭代对象内元素进行组合,但是结果不重复
listed = [‘a’,’b’,’c’,’d’]

for i in combinations(listed,3):
print(i)
#以下是输出结果
(‘a’, ‘b’, ‘c’)
(‘a’, ‘b’, ‘d’)
(‘a’, ‘c’, ‘d’)
(‘b’, ‘c’, ‘d’)
combinations_with_replacement:与 combinations 区别就是同一元素可以使用多次
listed = [‘a’,’b’,’c’] #由于结果数据太多,我减少源数据量

for i in combinations_with_replacement(listed,3):
print(i)

# 以下是输出结果
(‘a’, ‘a’, ‘a’)
(‘a’, ‘a’, ‘b’)
(‘a’, ‘a’, ‘c’)
(‘a’, ‘b’, ‘b’)
(‘a’, ‘b’, ‘c’)
(‘a’, ‘c’, ‘c’)
(‘b’, ‘b’, ‘b’)
(‘b’, ‘b’, ‘c’)
(‘b’, ‘c’, ‘c’)
(‘c’, ‘c’, ‘c’)
zip_longest:对多个数据按索引进行组合, 并根据迭代对象的大小,不足使用 fillvalue 默认值替代
a=[1,2,3]
b=[‘a’,’b’]

for i in zip_longest(a,b,fillvalue=”nihao”):
print(i)

for i in zip(a,b):
print(i)
#zip 是一个 python 内置函数,与 zip_longest 不同的是匹配到迭代对象最小的最后元素就结束
#结果对比:
zip_lengest: zip:
(1, ‘a’) (1, ‘a’)
(2, ‘b’) (2, ‘b’)
(3, ‘nihao’)

dropwhile: 对可迭代对象的元素依次进行函数过滤,遇到返回 False 的元素就停止
listed=[-1,0,-3,2,-5,4,2]

for i in dropwhile(lambda s:s<3,listed):
print(i)

# 输出结果:
4
2
product:可以说是 combinations 的升级版,对多个序列进行组合,且无重复
list1=[1,2,3]
list2=[4,5]
list3=[‘a’]

for i in product(list1,list2,list3):
print(i)
#结果:
(1, 4, ‘a’)
(1, 5, ‘a’)
(2, 4, ‘a’)
(2, 5, ‘a’)
(3, 4, ‘a’)
(3, 5, ‘a’)
islice: 对迭代器,可迭代对象进行切片操作
iter=(i for i in range(10))

for i in islice(iter,0,10,2):
print(i)
#结果为:
0
2
4
6
8
chain: 对多个可迭代对象进行组合
list1=[1,2,3]

set1={‘a’,’b’}

for i in chain(list1,set1):
print(i)
总结:itertools 这个模块可以解决以后我们对多个 iterable 进行组合的问题。

退出移动版