替换枚举以输出字符串

时间:2013-12-01 15:10:30

标签: python

我编写了一个代码,它读取包含几个段落的文本文件。我使用了枚举,但想用简单的循环替换enumerate()

file=open("file1.txt","r")
text="target"
for i, line in enumerate(file, 1):
    if text in line:
        print (i, line)

2 个答案:

答案 0 :(得分:3)

不知道你为什么要这样做,但这是等价的:

file=open("file1.txt","r")
text="target"
count=0
for line in file:
    count += 1
    if text in line:
        print (count, line)

答案 1 :(得分:1)

使用简单的生成器函数可以轻松替换

enumerate

def enumerate(iterable, start=0):
    for item in iterable:
        yield start, item
        start += 1