python-3.6 - 为什么我在 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)
为什么迭代目标文件它不会第二次打印结果。任何人都可以帮忙吗?
解决方案
在这种情况下, 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())
推荐阅读
- c# - 为什么我的代码不能在 Unity 中运行?统一 C#
- python - 如何解释这两个未压缩的 zlib 样本?
- css - AGM 地图打印显示打印输出中的间隙
- javascript - 关于为搜索框设置操作的问题
- python - futures.ProcessPoolExecutor 的不一致行为
- javascript - 测试 Cafe Headless 能见度检查
- list - Kotlin:将列表分组为地图的地图
- computer-vision - 为什么在图像上应用光流不能产生准确的下一帧
- javascript - 仅使用 javascript 获取未选中的复选框
- sql - 大型增长表sql的良好设计