迭代枚举对象两次
Iterating Enumeration Object Two Times
我创建了一个枚举对象,我通过枚举的方式迭代了一个列表。之后,我尝试了第二次,但我无法在解释器中获取任何输出。
myList = ["Red", "Blue", "Green", "Yellow"]
enum = enumerate(myList, 0)
for i in enum: # this printed the output
print(i)
for j in enum: # this did not print the output
print(j)
为什么我不能使用枚举对象两次?
enumerate
是一个迭代器,这意味着一旦它在单个 i.e 循环或调用 next
上运行,它对内存中值的引用已经耗尽,因此,仅仅是一个空的列表 ([]
) 将是第二次 next
在结构上调用或应用 for
时的结果。
但是,要解决此问题,您可以将结果转换为列表,或者将内容添加到另一个列表:
val = iter([i**2 for i in range(10)])
new_result = list(val)
>>>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#create a new structure:
val = iter([i**2 for i in range(10)])
other_val = [ for i in val]
或者,应用 next
:
val = iter([i**2 for i in range(10)])
while True:
try:
v = next(val)
#do something with v
except StopIteration:
break
我创建了一个枚举对象,我通过枚举的方式迭代了一个列表。之后,我尝试了第二次,但我无法在解释器中获取任何输出。
myList = ["Red", "Blue", "Green", "Yellow"]
enum = enumerate(myList, 0)
for i in enum: # this printed the output
print(i)
for j in enum: # this did not print the output
print(j)
为什么我不能使用枚举对象两次?
enumerate
是一个迭代器,这意味着一旦它在单个 i.e 循环或调用 next
上运行,它对内存中值的引用已经耗尽,因此,仅仅是一个空的列表 ([]
) 将是第二次 next
在结构上调用或应用 for
时的结果。
但是,要解决此问题,您可以将结果转换为列表,或者将内容添加到另一个列表:
val = iter([i**2 for i in range(10)])
new_result = list(val)
>>>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#create a new structure:
val = iter([i**2 for i in range(10)])
other_val = [ for i in val]
或者,应用 next
:
val = iter([i**2 for i in range(10)])
while True:
try:
v = next(val)
#do something with v
except StopIteration:
break