我有一个列表'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
是一个迭代器。迭代之后,它就筋疲力尽了,因此您的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
循环的每次迭代来“重置”文件迭代器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句