跳转到主要内容
模块 6 · 第 4 课(共 4)课程中的24/36~12 min
模块课程(4/4)

必备的 itertools

Python 公开了大量的迭代工具:有些是内置的(总是 可用),其他则位于标准的 itertools 模块中 图书馆。以下是最重要的。

enumerate:索引+值

当您在循环期间同时需要索引和元素时:

Python
for i, parola in enumerate(["a", "b", "c"]):
    print(i, parola)
# 0 a
# 1 b
# 2 c

# parte da un altro numero:
for i, parola in enumerate(["a", "b", "c"], start=1):
    print(i, parola)

zip:并行迭代

逐个元素组合多个可迭代对象:

Python
nomi = ["Ada", "Linus", "Grace"]
eta = [36, 54, 85]

for n, e in zip(nomi, eta):
    print(f"{n} ha {e} anni")

zip 在最短可迭代处停止。对于“长”拉链使用 itertools.zip_longest。

从两个并行列表构建一个字典:

Python
dict(zip(nomi, eta))
# {'Ada': 36, 'Linus': 54, 'Grace': 85}

itertools.chain:连接可迭代对象

Python
from itertools import chain
list(chain([1, 2], [3, 4], [5]))
# [1, 2, 3, 4, 5]

无需创建中间列表:对于文件、生成器等很有用。

itertools.count 和 repeat:无限迭代器

Python
from itertools import count, repeat

# count(start, step) — interi crescenti infiniti
for i in count(10, 2):
    if i > 20: break
    print(i)
# 10, 12, 14, 16, 18, 20

# repeat(x, n) — ripete lo stesso valore n volte (o all'infinito senza n)
list(repeat("ok", 3))   # ['ok', 'ok', 'ok']

itertools.combinations

给定的所有组合(无重复,与顺序无关) 长度:

Python
from itertools import combinations
list(combinations([1, 2, 3, 4], 2))
# [(1,2), (1,3), (1,4), (2,3), (2,4), (3,4)]

有序变体:permutations。具有重复的变体: combinations_with_replacement 和 product。

zip() 用于字典和不平衡迭代

一旦最短输入迭代用完,zip() 函数就会停止。如果您想要对元素进行配对并保留任何多余的值(使用 None 这样的默认值填充它们),您可以使用 itertools 模块中的 zip_longest() 。此外,您可以将 zip 结果直接传递到 dict() 以立即构建键值映射。

尝试一下

锻炼#python.m6.l4.e1
尝试:0加载中...

给定并行列表 `countries = ['Italia', 'Francia', 'Spagna']` 和 `capitals = ['Roma', 'Parigi', 'Madrid']`,将 `mapping` 构建为字典 {country: Capital}。评估“映射”。

正在加载编辑器...
显示提示

dict(zip(国家、首都))

3 次尝试后可用的解决方案

复习练习

锻炼#python.m6.l4.e2
尝试:0加载中...

给定 `words = ['ciao', 'mondo', 'python']`,将 `enumerated_items` 构建为从 i=1 开始的元组 (i, word) 列表。评估“enumerated_items”。

正在加载编辑器...
显示提示

枚举(words, start=1) → (i, value) 元组。

3 次尝试后可用的解决方案

额外的挑战

锻炼#python.m6.l4.e3
尝试:0加载中...

Given two lists `keys = ['a', 'b', 'c']` and `values = [10, 20, 30]`, use `zip` to pair them and convert the result into a dictionary. Store the resulting dictionary in `my_dict` and evaluate it.

正在加载编辑器...
显示提示

使用 dict(zip(keys, value)) 并将其分配给 my_dict。

3 次尝试后可用的解决方案