Chuyển đến nội dung chính
eLearner.app
Mô-đun 6 · Bài học 4 trong tổng số 424/36 trong khóa học~12 min
Bài học theo mô-đun (4/4)

Itertools cần thiết

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

tập thể dục#python.m6.l4.e1
Nỗ lực: 0Đang tải…

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

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

dict(zip(countries, capitals))

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#python.m6.l4.e2
Nỗ lực: 0Đang tải…

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

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử

Additional challenge

tập thể dục#python.m6.l4.e3
Nỗ lực: 0Đang tải…

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.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử