什么时候具体使用枚举函数,同样的任务可以用 for look 和 Zip 函数完成

When to use enumerate function specifically and can same task can be done with for look and Zip function

我不确定何时使用枚举函数,是否可以使用其他带有 zip 函数的 for 循环方法来完成此任务

enumerate(iterable, start=0)

枚举函数产生一个枚举对象,它只是一个包含元组的对象。元组包含两个值,第一个在元素的索引中,第二个是值。默认情况下,start 的值为 0。以下示例显示如何使用 enumerate 遍历列表。

l = ['Apple', 'Banana', 'guava', 'Strawberry', 'Pineapple']
enumerateObject = enumerate(l)

print(list(enumerateObject)) # an enumerate object

# using enumerateObject to loop
for ind, fruit in enumerateObject:
    print(ind, fruit)

Zip 函数用于一起遍历两个或多个可迭代对象(列表、元组、字典等)。 Zip 像枚举函数一样生成一个 zip 对象,其中包含相应元素的元组。 Zip 用于多个 iterable,而 enumerate 用于一个。

f = ['Apple', 'Banana', 'guava', 'Strawberry', 'Pineapple']
c = ['Red', 'yellow', 'green', 'pinkish red', 'Brown']

print(list(zip(f,c)))
for ele1, ele2 in zip(f, c):
    print(ele1, 'is', ele2, 'in colour')

要更好地理解它们,请尝试自己更改程序。请标记正确答案。

编码愉快!