【发布时间】:2017-04-12 13:20:56
【问题描述】:
我正在测试给定文件的输入/输出。每个文件都包含字符串,我将在该文件中搜索“s”并返回该文件中 s 位置的有序列表。该函数没有给出位置,而是给出了整行。为什么?
这是我的功能:
def locate(filename,s):
lookfor=s
new_list=[]
with open(filename) as my_file:
for num, line in enumerate(my_file):
if lookfor in line:
new_list.append(num)
new_list.sort()
return new_list
【问题讨论】:
-
sort()就地工作。所以写两条语句:new_list.sort()和return new_list。 -
你好
append(..)line。所以很明显它增加了整行。 -
是的,使用
append(line.index(s))。 -
@KelseyGreenwood:但是你说的locations是什么意思?列号还是行号?
-
在这种情况下,
for应该看起来像for num,line in enumerate(my_file):而你是append(num),所以不再有索引了。
标签: python-3.x file loops filereader