Python中的Itertools模块 – 实现高效率循环的迭代器函数

发布于 2023-06-26  277 次阅读


Please refresh the page if equations are not rendered correctly.
---------------------------------------------------------------

视频教程笔记:Python Tutorial: Itertools Module - Iterator Functions for Efficient Looping - YouTube

import itertools

counter = itertools.count(start=5, step=-2.5)
print(next(counter))
print(next(counter))
print(next(counter))

输出为:

5
2.5
0.0

data = [100, 200, 300, 400]
daily_data = list(zip(itertools.count(), data))
print(daily_data)

输出为:

[(0, 100), (1, 200), (2, 300), (3, 400)]

counter = itertools.cycle([1, 2, 3])
# counter = itertools.cycle(("On", "Off"))
n = 6
while n > 0:
    print(next(counter))
    n -= 1

输出为:

1
2
3
1
2
3

list(itertools.zip_longest(range(10), data))

输出为:

[(0, 100), (1, 200), (2, 300), (3, 400), (4, None), (5, None), (6, None), (7, None), (8, None), (9, None)]

counter = itertools.repeat(2, times=3)
print(list(counter))

cubics = map(pow, range(10), itertools.repeat(3))
print(list(cubics))

输出为:

[2, 2, 2]
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

# The square of the first element in the tuple.
squares = itertools.starmap(pow, [(0, 2), (1, 2), (2, 2), (3, 2)])
print(list(squares))

输出为:

[0, 1, 4, 9]

# itertools.combinations and itertools.permutations
letters = ['a', 'b', 'c', 'd']
numbers = [0, 1, 2, 3]
names = ['Corey', 'Nicole']

# Return the combinations of 2 elements from the letters list.
# For combinations, the order of the elements does not matter.
result = itertools.combinations(letters, 2)
for item in result:
    print(item)

输出为:

('a', 'b')
('a', 'c')
('a', 'd')
('b', 'c')
('b', 'd')
('c', 'd')

# Return the permutations of 2 elements from the letters list.
# For permutations, the order of the elements does matter.
result = itertools.permutations(letters, 2)
for item in result:
    print(item)

输出为:

('a', 'b')
('a', 'c')
('a', 'd')
('b', 'a')
('b', 'c')
('b', 'd')
('c', 'a')
('c', 'b')
('c', 'd')
('d', 'a')
('d', 'b')
('d', 'c')

# Cartesian product of the letters and numbers lists.
result = itertools.product(numbers, repeat=4)
for item in result:
    print(item)

输出为:

(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 0, 3)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 1, 3)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
(0, 2, 3)
(0, 3, 0)
(0, 3, 1)
(0, 3, 2)
(0, 3, 3)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 0, 3)
(1, 1, 0)
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(1, 2, 3)
(1, 3, 0)
(1, 3, 1)
(1, 3, 2)
(1, 3, 3)
(2, 0, 0)
(2, 0, 1)
(2, 0, 2)
(2, 0, 3)
(2, 1, 0)
(2, 1, 1)
(2, 1, 2)
(2, 1, 3)
(2, 2, 0)
(2, 2, 1)
(2, 2, 2)
(2, 2, 3)
(2, 3, 0)
(2, 3, 1)
(2, 3, 2)
(2, 3, 3)
(3, 0, 0)
(3, 0, 1)
(3, 0, 2)
(3, 0, 3)
(3, 1, 0)
(3, 1, 1)
(3, 1, 2)
(3, 1, 3)
(3, 2, 0)
(3, 2, 1)
(3, 2, 2)
(3, 2, 3)
(3, 3, 0)
(3, 3, 1)
(3, 3, 2)
(3, 3, 3)

Everything not saved will be lost.
最后更新于 2023-06-26