ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

itertools详解

2022-02-24 10:31:30  阅读:167  来源: 互联网

标签:迭代 list itertools 详解 print import iterable


Python中有一种特有的概念,称之为迭代器。
迭代器最大的特点是惰性求值,即只有当迭代至某个值时,才会对其进行计算,而不是一开始就计算出全部的值。
迭代器特别适合应用于大文件,无限集合等,因为无需将他们一次性传入内存中。
itertools是Python内置的模块,其中包含了一系列迭代器相关的函数和类。
本文将主要学习一下这些方法的使用。
 

count
count() 接收两个参数,第一个参数指定开始值,默认为 0,第二个参数指定步长,默认为 1。

作用是创建一个从 firstval (默认值为 0) 开始,以 step (默认值为 1) 为步长的的无限整数迭代器。

import itertools
nums = itertools.count(1, 2)
for i in nums:
    if i > 10:
        break
    print i
# 1
# 3
# 5
# 7
# 9
 

cycle
cycle(iterable)接收一个迭代器作为参数。

作用是对 iterable 中的元素反复执行循环,返回迭代器。

import itertools
nums = itertools.cycle("nian")
index = 0
for i in nums:
    index += 1
    if index > 10:
        break
    print i
# n
# i
# a
# n
# n
# i
# a
# n
# n
# i
 

repeat
repeat(object, times)接收两个参数,第一个参数是被重复的对象,第二个参数为重复的次数。

作用是重复生成多个对象。

import itertools
for element in itertools.repeat([1,2,3], 3):
    print element
 
# [1, 2, 3]
# [1, 2, 3]
# [1, 2, 3]
 

chain
chain的使用格式如下:chain(iterable1, iterable2, iterable3, ...)

作用是接收多个迭代器,并将他们连接起来返回一个新的迭代器。

from itertools import chain
for item in chain([1,2,3], [4,5,6]):
    print item
# 1
# 2
# 3
# 4
# 5
# 6
chain还有另外一个用法:即接收一个可迭代对象作为参数,并输出一个迭代器。

from itertools import chain
string = chain.from_iterable('ABCD')
print string.next()
# A
 

compress
compress的使用格式如下:compress(data, selectors)

作用如下:用于对数据进行筛选,当 selectors 的某个元素为 true 时,则保留 data 对应位置的元素,否则去除。

from itertools import compress
print list(compress('ABCDEF', [1, 1, 0, 1, 0, 1]))
# ['A', 'B', 'D', 'F']
print list(compress('ABCDEF', [1, 1, 0, 1]))
# ['A', 'B', 'D']
print list(compress('ABCDEF', [True, False, True]))
# ['A', 'C']
 

dropwhile
dropwhile的使用形式如下:dropwhile(function, iterable)

其中,第一个参数是一个函数,第二个参数是一个可迭代对象。

作用如下:对于 iterable 中的元素,如果 function(item) 为 true,则丢弃该元素,否则返回该项及所有后续项。

from itertools import dropwhile
print list(dropwhile(lambda x: x < 5, [1, 3, 6, 2, 1]))
# [6, 2, 1]
print list(dropwhile(lambda x: x > 3, [2, 1, 6, 5, 4]))
# [2, 1, 6, 5, 4]
 

groupby
groupby的使用形式如下:groupby(iterable[, keyfunc])

作用如下:iterable 是一个可迭代对象,keyfunc 是分组函数,用于对 iterable 的连续项进行分组。

如果不指定keyfunc,则默认对 iterable 中的连续相同值进行分组,返回一个 (key, sub-iterator) 的迭代器。

from itertools import groupby
for key, value_iter in groupby('aaabbbaaccd'): 
    print key, ':', list(value_iter)
# a : ['a', 'a', 'a']
# b : ['b', 'b', 'b']
# a : ['a', 'a']
# c : ['c', 'c']
# d : ['d']
data = ['a', 'bb', 'cc', 'ddd', 'eee', 'f']
for key, value_iter in groupby(data, len): 
    print key, ':', list(value_iter)
# 1 : ['a']
# 2 : ['bb', 'cc']
# 3 : ['ddd', 'eee']
# 1 : ['f']
data = ['a', 'bb', 'ccc', 'dd', 'eee', 'f']
for key, value_iter in groupby(data, len):
    print key, ':', list(value_iter)
# 1 : ['a']
# 2 : ['bb']
# 3 : ['ccc']
# 2 : ['dd']
# 3 : ['eee']
# 1 : ['f']
# Ps:函数处理后得到的值连续时会分为同一个组。
 

ifilter/ifilterfalse
形式如下:ifilter(function or None, iterable)

作用:将 iterable 中 function(item) 为 True 的元素组成一个迭代器返回,如果 function 是 None,则返回 iterable 中所有计算为 True 的项。

from itertools import ifilter
 
print list(ifilter(lambda x: x < 6, range(10)))
# [0, 1, 2, 3, 4, 5]
print list(ifilter(None, [0, 1, 2, 0, 3, 4]))
# [1, 2, 3, 4]
ifilterfalse与ifilter类似,将 iterable 中 function(item) 为 False 的元素组成一个迭代器返回。

from itertools import ifilterfalse
print list(ifilterfalse(lambda x: x < 6, range(10)))
# [6, 7, 8, 9]
print list(ifilter(None, [0, 1, 2, 0, 3, 4]))
# [0, 0]


islice
形式如下:islice(iterable, [start,] stop [, step])

其中,iterable 是可迭代对象,start 是开始索引,stop 是结束索引,step 是步长,start (默认为0)和 step(默认为1) 可选。

作用是将一个可迭代对象进行切割,返回一个新的迭代器。

from itertools import count, islice
print list(islice([10, 6, 2, 8, 1, 3, 9], 5))
# [10, 6, 2, 8, 1]
print list(islice(count(), 6))
# [0, 1, 2, 3, 4, 5]
print list(islice(count(), 3, 10))
# [3, 4, 5, 6, 7, 8, 9]
print list(islice(count(), 3, 10 ,2))
# [3, 5, 7, 9]


imap
形式如下:imap(func, iter1, iter2, iter3, ...)

作用是:imap 返回一个迭代器,元素为 func(i1, i2, i3, ...),i1,i2 等分别来源于 iter, iter2。

from itertools import imap
print imap(str, [1, 2, 3, 4])
# <itertools.imap object at 0x10556d050>
print list(imap(str, [1, 2, 3, 4]))
# ['1', '2', '3', '4']
print list(imap(pow, [2, 3, 10], [4, 2, 3]))
# [16, 9, 1000]


tee
形式如下:tee(iterable [,n])

作用是:用于从 iterable 创建 n 个独立的迭代器,以元组的形式返回,n 的默认值是 2。

from itertools import tee
print tee('abcd')   # n 默认为 2,创建两个独立的迭代器
# (<itertools.tee object at 0x1049957e8>, <itertools.tee object at 0x104995878>)
iter1, iter2 = tee('abcde')
print list(iter1)
# ['a', 'b', 'c', 'd', 'e']
print list(iter2)
# ['a', 'b', 'c', 'd', 'e']
print tee('abc', 3)  # 创建三个独立的迭代器
# (<itertools.tee object at 0x104995998>, <itertools.tee object at 0x1049959e0>, <itertools.tee object at 0x104995a28>)


takewhile
形式如下:takewhile(function, iterable)

其中,function是函数,iterable 是可迭代对象。

作用是:对于 iterable 中的元素,如果 function(item) 为 true,则保留该元素,只要 function(item) 为 false,则立即停止迭代。

from itertools import takewhile
print list(takewhile(lambda x: x < 5, [1, 3, 6, 2, 1]))
# [1, 3]
print list(takewhile(lambda x: x > 3, [2, 1, 6, 5, 4]))
# [] 


izip
形式如下:izip(iter1, iter2, ..., iterN)

作用是:用于将多个可迭代对象对应位置的元素作为一个元组,将所有元组『组成』一个迭代器,并返回。

Ps:如果某个可迭代对象不再生成值,则迭代停止。

from itertools import izip
 
for item in izip('ABCD', 'xy'):
    print item
# ('A', 'x')
# ('B', 'y')
for item in izip([1, 2, 3], ['a', 'b', 'c', 'd', 'e']):
    print item
# (1, 'a')
# (2, 'b')
# (3, 'c')


izip_longest
形式如下: izip_longest(iter1, iter2, ..., iterN, [fillvalue=None])

作用是:跟 izip 类似,但迭代过程会持续到所有可迭代对象的元素都被迭代完。

如果有指定 fillvalue,则会用其填充缺失的值,否则为 None。

from itertools import izip_longest
for item in izip_longest('ABCD', 'xy'):
    print item
# ('A', 'x')
# ('B', 'y')
# ('C', None)
# ('D', None)
for item in izip_longest('ABCD', 'xy', fillvalue='-'):
    print item
# ('A', 'x')
# ('B', 'y')
# ('C', '-')
# ('D', '-')


product
形式如下:product(iter1, iter2, ... iterN, [repeat=1])

其中,repeat 是一个关键字参数,用于指定重复生成序列的次数。

作用是:用于求多个可迭代对象的笛卡尔积,它跟嵌套的 for 循环等价。

from itertools import product
for item in product('ABCD', 'xy'):
    print item
# ('A', 'x')
# ('A', 'y')
# ('B', 'x')
# ('B', 'y')
# ('C', 'x')
# ('C', 'y')
# ('D', 'x')
# ('D', 'y')
print list(product('ab', range(3)))
# [('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2)]
print list(product((0,1), (0,1), (0,1)))
# [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
print list(product('ABC', repeat=2))
# [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]


permutations
形式如下:permutations(iterable[, r])

作用是:用于生成一个排列、

其中,r 指定生成排列的元素的长度,如果不指定,则默认为可迭代对象的元素长度。

from itertools import permutations
print permutations('ABC', 2)
# <itertools.permutations object at 0x1074d9c50>
print list(permutations('ABC', 2))
# [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
print list(permutations('ABC'))
# [('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]


combinations
形式如下:combinations(iterable, r)

作用是:用于求序列的组合,其中,r 指定生成组合的元素的长度。

from itertools import combinations
print list(combinations('ABC', 2))
# [('A', 'B'), ('A', 'C'), ('B', 'C')]


combinations_with_replacement
形式如下:combinations_with_replacement(iterable, r)

作用是:和 combinations 类似,但它生成的组合包含自身元素。

from itertools import combinations_with_replacement
print list(combinations_with_replacement('ABC', 2))
# [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]

 

标签:迭代,list,itertools,详解,print,import,iterable
来源: https://www.cnblogs.com/ai594ai/p/15930579.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有