首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用2个列表的双循环与使用2个文本文件的双循环相比-结果不同

使用2个列表的双循环与使用2个文本文件的双循环相比-结果不同
EN

Stack Overflow用户
提问于 2015-02-26 04:22:39
回答 2查看 38关注 0票数 1

所以我有两个迷你剧本。1产生我期望的输出,另一不产生输出。产生我期望的输出的第一个代码:

代码语言:javascript
复制
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() 

产出(如我所料):

代码语言:javascript
复制
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

在下一段代码中,我没有得到我想要的输出。它基本上与上面的代码相同,只是我直接处理文本文件,而不是先将它们转换为列表。然而,这令我困惑,为什么我没有得到完全相同的输出。

守则:

代码语言:javascript
复制
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()

输出:

代码语言:javascript
复制
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

既然我在每个代码中执行相同的double for循环,使用相同的print语句,那么为什么输出是不同的呢?

以下是文本文件的内容: cities.txt:

代码语言:javascript
复制
san diego
san francisco
tuscon
pheonix
sedona
baton rouge

test_file.txt:

代码语言:javascript
复制
san diego is the best place
Then there is new york state
And now we have tuscon in arizona
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-26 06:35:07

因为文件的对象是迭代器。若要将其转换为列表,请使用.readlines()函数。您的代码应该如下所示:

代码语言:javascript
复制
with open('cities.txt') as cities, open('tests.txt') as tests:
    for c in cities.readlines()
        for t in tests.readlines():
            print(c.rstrip() + " " + t.rstrip())

或者,您也可以使用itertools.product()来防止嵌套循环。在这种情况下,您的代码应该类似于:

代码语言:javascript
复制
with open('cities.txt') as cities, open('tests.txt') as tests:
    for c, t in itertools.product(cities.readlines(), tests.readlines()):
        print("{city} {test}".format(city=c,test=t))

注意:使用+代替直接追加字符串。使用.format()方法是较好的方法。

票数 1
EN

Stack Overflow用户

发布于 2015-02-26 05:13:34

因为文件是迭代器,而列表是列表。

当你做的时候

代码语言:javascript
复制
for t in test:
    pass # do anything here

到该循环结束时,您已经耗尽了迭代器。里面什么都没有了!你自己试试!:

代码语言:javascript
复制
with open('testfile.txt') as inf:
    for line in inf:
        print("There's a line here, I'm reading!")
    for line in inf:
        print("Turn lead into gold")

你会注意到这里完全缺乏炼金术。

您可以做的是在每次读取文件之前返回到文件的开头。

代码语言:javascript
复制
for c in cities:
    test.seek(0)
    # place the pointer at the beginning of the file
    for t in test:
        frobnicate_stuff()

不过,我更喜欢阅读每个文件一次并对列表进行操作,就像您在上面的示例中所做的那样。你也许可以用itertools.product做得更好

代码语言:javascript
复制
import itertools

with open('cities.txt') as cities, \
         open('test.txt') as test:
    city_lst = cities.readlines()
    test_lst = test.readlines()

for c, t in itertools.product(city_lst, test_lst):
    print(c.rstrip() + " " + t.rstrip())
    # or using string formatting:
    # # print("{} {}".format(c.rstrip(), t.rstrip()))

编辑

实际上,进一步的测试表明,itertools.product在使用它之前将每个迭代器内部化!这意味着我们可以:

代码语言:javascript
复制
with open('cities.txt') as cities, \
        open('tests.txt') as tests:
    for c, t in itertools.product(cities, tests):
        print(c.rstrip() + " " + t.rstrip())
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28734435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档