python parse 仅打印列表中的第一行

标签 python list

我有一个列表“a”,我需要用文本文件“hello.txt”的行打印列表中所有匹配的字母。但它只打印列表和行中的第一个单词而不是所有列表和行

a=['comp','graphics','card','part']

with open('hello.txt', 'r') as f:
    for key in a:
        for line in f:
            if key in line:
                print line, key

结果为:

comp and python
comp

期望的输出:

comp and python
comp
graphics and pixel
graphics
micro sd card
card
python part
part

请帮助我获得欲望输出。答案将不胜感激!

最佳答案

文件对象 f 是一个迭代器。 Once you've iterated it, it's exhausted ,因此您的 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 在评论中所建议的那样,使用原始循环并通过在外部 key 的每次迭代中调用 f.seek(0) 来“重置”文件迭代器 循环。

关于python parse 仅打印列表中的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24849562/

相关文章:

python - PIL Image.resize() 不调整图片大小

python - Tcl错误: bad window path name (Python)

c# - 如何从 List<object> 中删除所有对象,其中 object.variable 在任何其他 object.variable2 中至少存在一次?

Python 生成器函数和排列

c++ - 将链接列表转换为排序列表

java - 如何在java中创建列表数组

python - 在python中格式化输出

python - 尝试在我的 Tkinter/Python 应用程序中嵌入 native WINDOWS 命令​​行

python - 基于顶点绘制 3D 连接棱镜 matplotlib

list - 在列表中找到倒数第二个项目,请解释此解决方案