Python 不等于 'for' 迭代

标签 python for-loop

<分区>

在对文本文件和列表进行迭代期间,我发现了 for 循环的意外行为。 文本文件 test.txt 仅包含两个字符串:1) He said: 和 2) We said:。 第一个for+for循环

file_ = open('c:\\Python27\\test.txt', 'r')
list_ = ['Alpha','Bravo','Charlie']
try:
    for string in file_:
        for element in list_:
            print string, element
except StandardError:
    print 'Ooops'

返回完全符合预期的结果:

He said: Alpha
He said: Bravo
He said: Charlie
We said: Alpha
We said: Bravo
We said: Charlie

但是如果for顺序改为

file_ = open('c:\\Python27\\test.txt', 'r')
list_ = ['Alpha','Bravo','Charlie']
try:
    for element in list_:
        for string in file_:
            print string, element
except StandardError:
    print 'Ooops'

结果完全不同:

He said: Alpha
We said: Alpha

看起来第一个 for 变得可联合。为什么?

最佳答案

当您完成对文件的 for 循环时,您就“消费”了它。对于使用 file_.seek(0) 的外循环的每次迭代,您将不得不返回到它的开头。或者使用原来的循环顺序。

您可以使用这个简化示例复制该行为:

    for string in file_:
        print string

    for string in file_:
        print string

你会看到第二个循环什么也没做。

关于Python 不等于 'for' 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33110999/

相关文章:

python - 如何在 Atom 上配置 linter-flake8?

php - 计算php中字符串中四个字符的出现次数

c++ - 循环中的恒定条件 : compiler optimization

c - for 循环内的 for 循环

python - iPython locals() 中的 '_oh' 是什么?以及如何在标准 Python IDLE 中让本地人回来或创建新人

python - 关于使用 Ropevim 的任何指示?它是一个可用的库吗?

python - 不同环境下搜索结果不同

python - 使用 numpy/ctypes 公开 C 分配的内存缓冲区的更安全方法?

c# - CLR 正在优化我的 forloop 变量

python - 使用 python 编程时在迭代时修改列表