Python:itertools.islice无法循环运行 [英] Python: itertools.islice not working in a loop

查看:70
本文介绍了Python:itertools.islice无法循环运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

#opened file f
goto_line = num_lines #Total number of lines
while not found:
   line_str = next(itertools.islice(f, goto_line - 1, goto_line))
   goto_line = goto_line/2
   #checks for data, sets found to True if needed

line_str在第一次通过时是正确的,但是此后的每个通过都读取了应该读取的另一行.

line_str is correct the first pass, but every pass after that is reading a different line then it should.

因此,例如,goto_line开始时为1000.它读取行1000很好.然后,下一个循环goto_line是500,但它不读取第500行.它读取的行更接近1000.

So for example, goto_line starts off as 1000. It reads line 1000 just fine. Then the next loop, goto_line is 500 but it doesn't read line 500. It reads some line closer to 1000.

我正在尝试读取大文件中的特定行,而不读取多余的内容.有时它会向后跳到一条线,有时又跳到一条线.

I'm trying to read specific lines in a large file without reading more than necessary. Sometimes it jumps backwards to a line and sometimes forward.

我确实尝试过线缓存,但是我通常不会在同一文件上多次运行此代码.

I did try linecache, but I typically don't run this code more than once on the same file.

推荐答案

Python迭代器只能使用一次.通过示例最容易看出这一点.以下代码

Python iterators can be consumed only once. This is easiest seen by example. The following code

from itertools import islice
a = range(10)
i = iter(a)
print list(islice(i, 1, 3))
print list(islice(i, 1, 3))
print list(islice(i, 1, 3))
print list(islice(i, 1, 3))

打印

[1, 2]
[4, 5]
[7, 8]
[]

切片总是从上次停止的地方开始.

The slicing always starts where we stopped last time.

使代码工作最简单的方法是使用f.readlines()获取文件中各行的列表,然后使用常规的Python列表切片[i:j].如果您确实要使用islice(),则可以每次使用f.seek(0)从头开始读取文件,但这效率很低.

The easiest way to make your code work is to use the f.readlines() to get a list of the lines in the file and then use normal Python list slicing [i:j]. If you really want to use islice(), you could start reading the file from the beginning each time by using f.seek(0), but this will be very inefficient.

这篇关于Python:itertools.islice无法循环运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆