Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我怎样才能把一份文件翻两遍?_Python_File_For Loop_Iteration - Fatal编程技术网

Python 我怎样才能把一份文件翻两遍?

Python 我怎样才能把一份文件翻两遍?,python,file,for-loop,iteration,Python,File,For Loop,Iteration,我有以下代码: for line in AAA: print line for line_again in AAA: print line_again 第二次打印为空 我怎么能把清单翻两遍呢?如何回退指针?正如其他人评论的那样,您可能有一个迭代器,而不是列表;可以使用从同一个iterable获取两个独立的迭代器: >>> from itertools import tee >>> a = [1, 2, 3] >>>

我有以下代码:

for line in AAA:   
    print line
for line_again in AAA:   
    print line_again
第二次打印为空


我怎么能把清单翻两遍呢?如何回退指针?

正如其他人评论的那样,您可能有一个迭代器,而不是列表;可以使用从同一个iterable获取两个独立的迭代器:

>>> from itertools import tee
>>> a = [1, 2, 3]
>>> fst, snd = tee(iter(a))  # two copies of same iterator
>>>
>>> list(fst)  # exhaust the first iterator
[1, 2, 3]
>>> list(snd)  # now use the 2nd one
[1, 2, 3]

这将使设置指针返回起点。

您确定
AAA
是列表吗?最有可能是迭代器。要查看,请尝试
打印类型(AAA)
您所说的“第二次打印为空”是什么意思。AAA的类型是什么?AAA是一个文件。openedA文件不是一个列表。我不想创建另一个名称不同的列表-只想将指针移回并运行循环again@NimrodB它不会创建另一个列表;它创建一个独立的迭代器;尽管如此,迭代器并没有列出-它的名称不同(我找到了我需要的答案-seek(0,0)),谢谢
AAA.seek(0,0)