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

必备的 itertools

Python exposes plenty of iteration tools: some are built-in (always available), others live in the itertools module of the standard library. Here are the most important ones.

enumerate: index + value

When you need both the index and the element during a loop:

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: iterate in parallel

Combines multiple iterables element by element:

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

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

zip stops at the shortest iterable. For a "long" zip use itertools.zip_longest.

Building a dict from two parallel lists:

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

itertools.chain: concatenate iterables

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

Without creating an intermediate list: useful for files, generators, etc.

itertools.count and repeat: infinite iterators

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

All combinations (without repetitions, order-independent) of a given length:

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

Ordered variant: permutations. Variants with repetition: combinations_with_replacement and product.

zip() for dictionaries and unbalanced iterables

The zip() function stops as soon as the shortest input iterable is exhausted. If you want to pair elements and keep any excess values (filling them with a default value like None), you can use zip_longest() from the itertools module. Additionally, you can pass a zip result directly to dict() to instantly build a key-value map.

Try it

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

Given the parallel lists `countries = ['Italia', 'Francia', 'Spagna']` and `capitals = ['Roma', 'Parigi', 'Madrid']`, build `mapping` as a dict {country: capital}. Evaluate `mapping`.

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

dict(zip(countries, capitals))

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

Review exercise

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

Given `words = ['ciao', 'mondo', 'python']`, build `enumerated_items` as a list of tuples (i, word) starting from i=1. Evaluate `enumerated_items`.

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

enumerate(words, start=1) → (i, value) tuples.

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

Additional challenge

锻炼#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.

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

Use dict(zip(keys, values)) and assign it to my_dict.

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