[英]Python, how can I set iterator of enumerate to 0 while reading same file again and again
with open("...txt") as fp:
for i, line in enumerate(fp):
if some condition :
i=0
fp.seek(0)
文本很大,数据的GB数很大,所以我使用枚举。 我需要处理这个巨大的文件数千次,所以为了提高效率,我决定第一次打开它。 但是,尽管此代码有效,但i
并没有变为0,而是继续递增。 我需要将其设为零,因为我需要第i
行的位置。 每次乘以数十亿*几千并进行一些模运算只是效率低下。
所以我的问题是,当我回到文件开头时,如何将i
设置为零? 在此先感谢(我使用python 3.6)
你总是可以使自己的复位枚举,但有可能是更好的方法做你真正想做的事情。
尽管如此,这还是一个可重置的枚举器的样子:
def reset_enumerate(thing, start=0):
x = start
for t in thing:
val = yield t, x
if val is not None:
x = val
else:
x += 1
然后,您将像这样使用它:
r = reset_enumerate(range(10))
for i, num in r:
print('i:', i, 'num:', num)
if i == 5:
i, num = r.send(0)
print('i:', i, 'num:', num)
这是一个如何模拟类似场景的示例:
假设我有一个名为input.txt
的文件,其中包含这种数据:
1
2
3
码:
j = 0
with open('input.txt', 'r') as f:
for k in f:
# A break condition
# If not we'll face an infinite loop
if j > 4:
break
if k.strip() == '2':
f.seek(0)
print("Return to position 0")
# Don't forget to increment j
# Otherwise, we'll end up with an infinite loop
j += 1
print(k.strip())
将输出:
1
Return to position 0
2
1
Return to position 0
2
1
Return to position 0
2
1
Return to position 0
2
1
Return to position 0
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.