我不确定何时使用枚举函数,这个任务是否可以与其他包含zip函数的for循环方法一起完成?
发布于 2022-05-30 08:05:09
enumerate(iterable, start=0)枚举函数生成一个枚举对象,它只是一个包含元组的对象。元组包含两个值,一个在元素的索引中,第二个在值中。默认情况下,开始值为0。下面的示例演示如何使用枚举遍历列表。
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用于多个迭代,而枚举则用于一个。
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')要更好地理解它们,请自己尝试改变程序。请把答案记在正确的位置。
编码愉快!
https://stackoverflow.com/questions/72430614
复制相似问题