栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python parse只打印列表的第一行

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python parse只打印列表的第一行

文件对象

f
是一个迭代器。迭代之后,它就筋疲力尽了,因此您的
for line inf:
循环仅适用于第一个键。将这些行存储在中
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
循环的每次迭代来“重置”文件迭代器。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/652133.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号