cong wang
2024-06-03

python迭代器

python迭代器

基础概念

  • 可迭代对象(iterable):直接作用于for循环的对象;可使用iter()转换成迭代器。
  • 迭代器(iterator):使用next()函数调用并不断返回下一个值的对象

迭代器

无穷迭代器

无穷迭代器:count()、cycle()、repeat()

count

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

import itertools
i = 0
for base in itertools.count(start=10, step=2):
if i > 5:
break
print(base)
i += 1

# 10
# 12
# 14
# 16
# 18
# 20

cycle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

import itertools
i = 0
for base in itertools.cycle('ATCG'):
if i > 10:
break
print(base)
i += 1

# A
# T
# C
# G
# A
# T
# C
# G
# A
# T
# C

repeat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

import itertools
for base in itertools.repeat('abc', 3):
print(base)

# abc
# abc
# abc

for base in itertools.repeat(['a','b','c'], 3):
print(base)

# ['a', 'b', 'c']
# ['a', 'b', 'c']
# ['a', 'b', 'c']

有限迭代器

有限迭代器:accumulate()、chain()

accumulate

1
2
3
4
5
6
7
8
9
10
11
12
13

import itertools
for base in itertools.accumulate([1, 2, 3, 4, 5]):
print(base)

# 1
# 3
# 6
# 10
# 15



参考

reference:https://docs.python.org/zh-cn/3/library/itertools.html