为什么我在 python 使用的列表和要迭代的对象中得到不同的 'for' 循环结果?

Why am I getting different results for 'for' loop in python used list and a object to iterate through?

当我使用for循环迭代对象时

arr = map(int, input().split())

for j in arr: # this print's results
    print(j)

for i in arr: # this doesn't print any results
    print(i)

另一方面

any = [5,8,6,4]

for i in any:  # this print's results
    print(i)

for j in any: # this also print's results
    print(j)

为什么迭代目标文件没有第二次打印结果。有人可以帮忙吗?

在这种情况下,input().split() 很可能是生成器对象。 生成器对象只能使用一次。使用 中的示例生成器函数,我们可以重现您的问题

# Create generator function
def generator(n):
  a = 1

  for _ in range(n):
    yield a
    a += 1

# Set vars
a = [1 ,2, 3, 4]
b = generator(4)

## type(a) ->  list
## type(b) -> generator

# Print each var

# First time through list a
for i in a:
  print(i)
## prints 1, 2, 3, 4

# First time through list b
for i in b:
  print(i)
## prints 1, 2, 3, 4

# Second time through list a
for i in a:
  print(i)
## prints 1, 2, 3, 4

# Second time through list b
for i in b:
  print(i)

# Prints nothing

您可以通过将 input().split() 转换为列表来解决此问题。 IE list(input().split())

我不知道到底是什么原因,我猜可能与iterators有关,我已经遇到这个问题很长时间了,这是我使用最多的解决方案之一时间是将 map 的结果转换为 list,例如:

arr = list(map(int, input().split()))

for j in arr: # this will print the results
    print(j)

for i in arr: # this also will print the results
    print(i)

根据 Python 3 documents,map() returns 一个迭代器。您只能使用一次迭代器。

查看类似问题Python - Printing Map Object Issue