返回迭代器:zip、enumerate 函数

149 阅读1分钟

zip函数

zip 将多个可迭代的对象按照索引进行配对,返回新的迭代器,其中每个元素是一个包含来自输入可迭代对象相同索引位置的元素的元组。如果可迭代对象的长度不一致,按照最短进行配对。

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
cities = ('New York', 'London', 'Paris')

# 使用 zip() 函数配对多个可迭代对象
for name, age, city in zip(names, ages, cities):
    print(f'{name} is {age} years old and lives in {city}')
Alice is 25 years old and lives in New York
Bob is 30 years old and lives in London
Charlie is 35 years old and lives in Paris

解压缩

list(zip([1, 2, 3], [4, 5, 6]))  # [(1, 4), (2, 5), (3, 6)]
a = [1, 2, 3], b = ["a", "b", "c"]
z = zip(a, b)  # 压缩:[(1, "a"), (2, "b"), (3, "c")]
zip(*z)  # 解压缩:[(1, 2, 3), ("a", "b", "c")]

enumerate函数

enumerate() 是 Python 内置函数之一,用于将一个可迭代对象(如列表、元组、字符串等)组合为一个枚举对象,同时返回元素的索引和对应的

enumerate(iterable, start=0)其中,iterable 是一个可迭代对象,可以是列表、元组、字符串等。start 是可选参数,表示索引的起始值,默认为 0。

fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):
    print(index, fruit)
0 apple
1 banana
2 cherry