所以我有两个小脚本。1产生我期望的输出,而另一个不产生。产生我期望的输出的第一个代码:
with open('cities.txt', 'r') as cities, \
open('test_file.txt', 'r') as test:
space = " "
city_lst = []
test_lst = []
for c in cities:
city_lst.append(c)
for t in test:
test_lst.append(t)
for city in city_lst:
for tes in test_lst:
print city.rstrip(),space,tes.rstrip()
输出(如我所料):
san diego san diego is the best place
san diego Then there is new york state
san diego And now we have tuscon in arizona
san francisco san diego is the best place
san francisco Then there is new york state
san francisco And now we have tuscon in arizona
tuscon san diego is the best place
tuscon Then there is new york state
tuscon And now we have tuscon in arizona
pheonix san diego is the best place
pheonix Then there is new york state
pheonix And now we have tuscon in arizona
sedona san diego is the best place
sedona Then there is new york state
sedona And now we have tuscon in arizona
baton rouge san diego is the best place
baton rouge Then there is new york state
baton rouge And now we have tuscon in arizona
在下一段代码中,我没有得到我认为会得到的输出。它基本上与上面的代码相同,只是我直接处理文本文件,而不是首先将它们转换为列表。然而,这让我困惑,为什么我没有得到完全相同的输出
代码:
with open('cities.txt', 'r') as cities, \
open('test_file.txt', 'r') as test:
space = " "
for c in cities:
for t in test:
print c.rstrip(), space, t.rstrip()
输出:
san diego san diego is the best place
san diego Then there is new york state
san diego And now we have tuscon in arizona
既然我在每段代码中使用相同的print语句执行相同的double for循环,为什么输出会有差异呢
以下是文本文件的内容: 城市.txt:
san diego
san francisco
tuscon
pheonix
sedona
baton rouge
测试文件.txt:
san diego is the best place
Then there is new york state
And now we have tuscon in arizona
因为文件是迭代器,而列表是列表
当你这么做的时候
循环结束时,您已经耗尽了迭代器。里面什么都没有了!你自己试试!:
你会注意到这里完全没有炼金术
您可以做的是在每次读取文件之前
seek
返回到文件的开头不过,我更喜欢一次读取每个文件并对列表进行操作,就像您在上面的示例中所做的那样。使用^{} 可能会做得更好:
编辑
事实上,进一步的测试表明^{} 在使用每个迭代器之前将其内部化!这意味着我们可以:
因为文件的对象是迭代器。要将其转换为列表,请使用
.readlines()
函数。你的代码应该是这样的:或者,也可以使用
itertools.product()
来防止嵌套循环。在这种情况下,您的代码应该如下所示:注意:不是使用
+
直接追加字符串。使用.format()
方法是更好的方法相关问题 更多 >
编程相关推荐