python怎么只打印其中一行_python parse只打印列表的第一行

1586010002-jmsa.png

I have a list 'a',where I need to print all the matching letters of the list with the line of a text file 'hello.txt'.But it only prints the first word from the list and line instead of all the list and lines

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

It results as:

comp and python

comp

Desired output:

comp and python

comp

graphics and pixel

graphics

micro sd card

card

python part

part

Please help me to get desires output.Answers willbe appreciated!

解决方案

The file-object f is an iterator. Once you've iterated it, it's exhausted, thus your for line in f: loop will only work for the first key. Store the lines in a list, then it should work.

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

Alternatively, you could also swap the loops, so you iterate the file only once. This could be better if the file is really big, as you won't have to load all it's contents into memory at once. Of course, this way your output could be slights different (in a different order).

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

Or, as suggested by Lukas in the comments, use your original loop and 'reset' the file-iterator by calling f.seek(0) in each iteration of the outer key loop.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值