gpt4 book ai didi

Python 不等于 'for' 迭代

转载 作者:太空宇宙 更新时间:2023-11-04 08:53:08 26 4
gpt4 key购买 nike

<分区>

在对文本文件和列表进行迭代期间,我发现了 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 变得可联合。为什么?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com