首页 > 解决方案 > 为什么我在 python 使用列表中的“for”循环和要迭代的对象中得到不同的结果?

问题描述

当我使用 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)

为什么迭代目标文件它不会第二次打印结果。任何人都可以帮忙吗?

标签: python-3.6

解决方案


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

# 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())


推荐阅读