【问题标题】:how to can i go over a file twice?我怎样才能把一个文件翻两次?
【发布时间】:2015-02-12 17:44:36
【问题描述】:

我有以下代码:

for line in AAA:   
    print line
for line_again in AAA:   
    print line_again

第二次打印是空的。

我怎样才能把列表翻两遍?如何设置指针?

【问题讨论】:

  • 您确定AAA 是列表吗?很可能它是一个迭代器。
  • 要查看,请尝试print type(AAA)
  • “第二次打印是空的”是什么意思。 AAA的类型是什么?
  • AAA 是我打开的文件
  • 文件不是列表。

标签: python file for-loop iteration


【解决方案1】:

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

>>> 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]

【讨论】:

  • 我不想创建另一个名称不同的列表 - 只想将指针移回并再次运行循环
  • @NimrodB 它不会创建另一个列表;它创建了一个独立的迭代器;迭代器不是列表
  • 尽管如此 - 它的名称不同(我找到了我需要的答案 - seek(0,0) )谢谢
【解决方案2】:
AAA.seek(0,0)

这会将设置的指针返回到起点。

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多