在阅读文件时,我知道可以通过next()
获取下一行,但是有一个函数,例如,prev()
可以转到上一行吗?
与此类似,在循环浏览文件时,是否可以在目标行之后获取第二行? next()
只会在字符串后面返回该行。
答案 0 :(得分:3)
不,没有对手。您可以将以前的行存储在变量中:
prev = None
for something in an_iterator:
# do something with prev
prev = something
对于多件商品,您可以使用collections.deque()
object:
from collections import deque
five_prev = deque(an_iterator, maxlen=5)
for something in an_iterator:
five_lines_back = five_prev.popleft()
# ...
five_prev.append(something)
在从迭代中检索它之前,您无法知道接下来会发生什么,但您当然可以跟踪之前的内容。
您不仅限于拨打next()
一次;如果您需要从iterable中检索两行,请两次调用next()
,或使用next()
Array
(
[11] => Array
(
[0] => Array
(
[count] => 2
[price] => 1000
[total] => 2000
)
[1] => Array
(
[count] => 0
[price] => 124
[total] => 0
)
[2] => Array
(
[count] => 0
[price] => 1000
[total] => 0
)
[3] => Array
(
[count] => 0
[price] => 2345
[total] => 0
)
)
[12] => Array
(
[0] => Array
(
[count] => 0
[price] => 1000
[total] => 0
)
[1] => Array
(
[count] => 1
[price] => 124
[total] => 124
)
[2] => Array
(
[count] => 0
[price] => 1000
[total] => 0
)
[3] => Array
(
[count] => 0
[price] => 2345
[total] => 0
)
)
)
来检索多个项目。