Python itertools模块常用函数详解与实战示例
本文详细介绍Python标准库itertools模块的核心功能,涵盖chain、count、filterfalse、compress、starmap、repeat、dropwhile、takewhile、islice、product、permutations及combinations等常用函数的用法与参数说明,并提供质数求和等实战应用示例,帮助开发者高效处理迭代数据。
itertools模块概述与导入
Python标准库itertools模块介绍
itertools是Python内置的强大模块,使用简单且功能丰富。本文尝试对其主要功能进行汇总整理,并提供基础应用示例;若需补充其他用法,欢迎交流补充。
在Python中使用itertools模块非常简单,只需执行一句导入语句:import itertools。
基础迭代与链接:chain
chain()
顾名思义,chain()函数用于将多个列表、元组或可迭代对象链接在一起,并返回一个可迭代对象。
letters = ['a', 'b', 'c', 'd', 'e', 'f']
booleans = [1, 0, 1, 0, 0, 1]
print(list(itertools.chain(letters,booleans)))
#输出:['a', 'b', 'c', 'd', 'e', 'f', 1, 0, 1, 0, 0, 1]
print(tuple(itertools.chain(letters,letters[3:])))
#输出('a', 'b', 'c', 'd', 'e', 'f', 'd', 'e', 'f')
print(set(itertools.chain(letters,letters[3:])))
#输出:{'a', 'd', 'b', 'e', 'c', 'f'}
print(list(itertools.chain(letters,letters[3:])))
#输出:['a', 'b', 'c', 'd', 'e', 'f', 'd', 'e', 'f']
for item in list(itertools.chain(letters,booleans)):
print(item)
无限序列生成:count
count()
该函数用于生成无界限的无限序列,语法为count(start=0, step=1)。例如,从100开始,步长为2,循环10次并打印对应值;注意必须手动添加break语句,因为count()会无限循环下去。
i = 0
for item in itertools.count(100,2):
i += 1
if i > 10 : break
print(item)
数据过滤与压缩:filterfalse与compress
filterfalse()
Python的filterfalse(condition, data)函数用于迭代过滤条件为False的数据。如果未提供条件,则返回data中值为False的项;
booleans = [1, 0, 1, 0, 0, 1]
numbers = [23, 20, 44, 32, 7, 12]
print(list(itertools.filterfalse(None,booleans)))
#输出:[0, 0, 0]
print(list(itertools.filterfalse(lambda x : x < 20,numbers)))
#输出:[23, 20, 44, 32]
compress()
该函数根据b集合中元素的真值,返回a集中对应的元素,从而筛选出我们需要的元素。
print(list(itertools.compress(letters,booleans)))
# ['a', 'c', 'f']
函数映射与重复:starmap与repeat
starmap()
针对列表中的每一项调用指定函数。语法为starmap(func, list[]);
starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
>>> from itertools import *
>>> x = starmap(max,[[5,14,5],[2,34,6],[3,5,2]])
>>> for i in x:
>>> print (i)
14
34
5
repeat()
语法为repeat(object[, times]),用于将对象重复times次;
repeat(10, 3) --> 10 10 10
序列截取与过滤:dropwhile、takewhile与islice
dropwhile()
语法为dropwhile(func, seq);当函数f执行返回False时,开始迭代序列。
dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
takewhile()
语法为takewhile(predicate, iterable);返回序列,当predicate为True时截止。
takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
islice()
语法为islice(seq[, start], stop[, step]);返回序列seq从start开始到stop结束,步长为step的元素的迭代器。
for i in islice("abcdef", 0, 4, 2):#a, c
print i
组合与排列:product、permutations与combinations
product()
语法为product(iter1, iter2, ... iterN, [repeat=1]);创建一个迭代器,生成表示item1、item2等中项目的笛卡尔积的元组。repeat是一个关键字参数,用于指定重复生成序列的次数。
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
for i in product([1, 2, 3], [4, 5], [6, 7]):
print i
(1, 4, 6)
(1, 4, 7)
(1, 5, 6)
(1, 5, 7)
(2, 4, 6)
(2, 4, 7)
(2, 5, 6)
(2, 5, 7)
(3, 4, 6)
(3, 4, 7)
(3, 5, 6)
(3, 5, 7)
permutations()
语法为permutations(p[, r]);返回p中任意取r个元素做排列的元组的迭代器。
for i in permutations([1, 2, 3], 3):
print i
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
combinations()
语法为combinations(iterable, r);创建一个迭代器,返回iterable中所有长度为r的子序列,返回的子序列中的项按输入iterable中的顺序排序。
注意:combinations不带重复。
for i in combinations([1, 2, 3], 2):
print i
(1, 2)
(1, 3)
(2, 3)
combinations_with_replacement()
同上,但带重复。例子:
for i in combinations_with_replacement([1, 2, 3], 2):
print i
(1, 1)
(1, 2)
(1, 3)
(2, 2)
(2, 3)
(3, 3)
实战应用示例
应用示例
求质数序列中1,3,5,7,9,11,13,15三个数之和为35的三个数;
def get_three_data(data_list,amount):
for data in list(itertools.combinations(data_list, 3)):
if sum(data) == amount:
print(data)
#(7, 13, 15)
更多Python标准库使用方法请点击下面的相关文章
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









