您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python parse只打印列表的第一行

python parse只打印列表的第一行

文件对象f一个迭代器。迭代之后,它就筋疲力尽了,因此您的for line in f:循环仅适用于第一个键。将这些行存储在中list,这样就可以了。

a=['comp','graphics','card','part']
with open('hello.txt', 'r') as f:
    lines = f.readlines()  # loop the file once and store contents in list
    for key in a:
        for line in lines:
            if key in line:
                print line, key

另外,您也可以交换循环,因此只将文件迭代一次。如果文件很大,这可能会更好,因为您不必一次将所有内容加载到内存中。当然,这样您的输出可能会略有不同(以不同的顺序)。

a=['comp','graphics','card','part']
with open('hello.txt', 'r') as f:
    for line in f:     # Now the file is only done once...
        for key in a:  # ... and the key loop is done multiple times
            if key in line:
                print line, key

或者,如Lukas在评论中所建议的那样,使用原始循环并通过调用f.seek(0)外部key循环的每次迭代来“重置”文件迭代器。

python 2022/1/1 18:38:14 有242人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶