Python 函数式编程 -- itertools 模块

2023-04-10 10:55:26

– Start

点击此处观看本系列配套视频。


itertools 模块提供了非常多的方法。

Infinite iterators

Iterator Arguments Results Example
count() start, [step] start, start+step, start+2*step, … count(10) --> 10 11 12 13 14 …
cycle() p p0, p1, … plast, p0, p1, … cycle(‘ABCD’) --> A B C D A B C D …
repeat() elem [,n] elem, elem, elem, … endlessly or up to n times repeat(10, 3) --> 10 10 10
import itertools as it

# count
count_iter = it.count(10)
print([next(count_iter) for i in range(5)])

# cycle
cycle_iter = it.cycle('ABCD')
print([next(cycle_iter) for i in range(8)])

# repeat
repeat_iter = it.repeat(10, 3)
print([next(repeat_iter) for i in range(3)])

Iterators terminating on the shortest input sequence

Iterator Arguments Results Example
accumulate() p [,func] p0, p0+p1, p0+p1+p2, … accumulate([1,2,3,4,5]) --> 1 3 6 10 15
chain() p, q, … p0, p1, … plast, q0, q1, … chain(‘ABC’, ‘DEF’) --> A B C D E F
chain.from_iterable() iterable p0, p1, … plast, q0, q1, … chain.from_iterable([‘ABC’, ‘DEF’]) --> A B C D E F
compress() data, selectors (d[0] if s[0]), (d[1] if s[1]), … compress(‘ABCDEF’, [1,0,1,0,1,1]) --> A C E F
dropwhile() pred, seq seq[n], seq[n+1], starting when pred fails dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
filterfalse() pred, seq elements of seq where pred(elem) is false filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
groupby() iterable[, key] sub-iterators grouped by value of key(v)
islice() seq, [start,] stop [, step] elements from seq[start:stop:step] islice(‘ABCDEFG’, 2, None) --> C D E F G
starmap() func, seq func(*seq[0]), func(*seq[1]), … starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
takewhile() pred, seq seq[0], seq[1], until pred fails takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
tee() it, n it1, it2, … itn splits one iterator into n
zip_longest() p, q, … (p[0], q[0]), (p[1], q[1]), … zip_longest(‘ABCD’, ‘xy’, fillvalue=’-’) --> Ax By C- D-
import itertools as it

# accumulate
print(list(it.accumulate([1, 2, 3, 4, 5])))

# chain
print(list(it.chain('ABC', 'DEF')))

# chain.from_iterable
print(list(it.chain.from_iterable(['ABC', 'DEF'])))

# compress
print(list(it.compress('ABCDEF', [1, 0, 1, 0, 1, 1])))

# dropwhile
print(list(it.dropwhile(lambda x: x < 5, [1, 4, 6, 4, 1])))

# filterfalse
print(list(it.filterfalse(lambda x: x % 2, range(10))))

# groupby
print([list(g) for k, g in it.groupby('AAAABBBCCD')])

# islice
print(list(it.islice('ABCDEFG', 2, None)))

# starmap
print(list(it.starmap(pow, [(2,5), (3,2), (10,3)])))

# takewhile
print(list(it.takewhile(lambda x: x < 5, [1, 4, 6, 4, 1])))

# takewhile
print(list(it.takewhile(lambda x: x < 5, [1, 4, 6, 4, 1])))

# tee
my_iter = iter(range(10))
it1, it2 = it.tee(my_iter, 2)
print(list(it1))
print(list(it2))

# zip_longest
print(list(it.zip_longest('ABCD', 'xy', fillvalue='-')))

Combinatoric iterators

Iterator Arguments Results
product() p, q, … [repeat=1] cartesian product, equivalent to a nested for-loop
permutations() p[, r] r-length tuples, all possible orderings, no repeated elements
combinations() p, r r-length tuples, in sorted order, no repeated elements
combinations_with_replacement() p, r r-length tuples, in sorted order, with repeated elements
product(‘ABCD’, repeat=2) AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations(‘ABCD’, 2) AB AC AD BA BC BD CA CB CD DA DB DC
combinations(‘ABCD’, 2) AB AC AD BC BD CD
combinations_with_replacement(‘ABCD’, 2) AA AB AC AD BB BC BD CC CD DD
import itertools as it

# product
print(list(it.product('ABCD', repeat=2)))

# permutations
# n! / (n-r)!
print(list(it.permutations('ABCD', 2)))

# combinations
# n! / r! / (n-r)!
print(list(it.combinations('ABCD', 2)))

# combinations_with_replacement
# (n+r-1)! / r! / (n-1)!
print(list(it.combinations_with_replacement('ABCD', 2)))

自定义函数

尽管 Python 提供了大量的函数为函数式编程服务,有时候我们还是需要自定义函数,一是为了实现特殊功能,二是为了封装已有函数使可读性更好。如,我们想实现类似 SQL 取前 10 条数据的功能,我们可以这样写。

list(islice(iterable, n))

为了可读性更好,我们可以定义一个函数来封装它。

def top(n, iterable):
    return list(islice(iterable, n))

自定义函数要遵循 currying 原则,一个函数只实现一个功能,每次只处理一个元素,避免消耗内存,返回一个可迭代对象。

– 更多参见:Python 精萃
– 声 明:转载请注明出处
– Last Updated on 2018-10-05
– Written by ShangBo on 2018-10-04
– End

  • 作者:shangboerds
  • 原文链接:https://blog.csdn.net/shangboerds/article/details/82940846
    更新时间:2023-04-10 10:55:26