【问题标题】:Python: ValueError: Mixing iteration and read methods would lose dataPython:ValueError:混合迭代和读取方法会丢失数据
【发布时间】:2017-02-23 18:12:52
【问题描述】:

执行下面的脚本时,我得到:

ValueError:混合迭代和读取方法会丢失数据

我知道这是因为 num 在第一个 for 循环中,而 last_host 是 num 的依赖项,但我不知道如何解决这个问题。

#!/usr/bin/env python2
import datetime as dt
import glob as glob
import os as os
import shutil as shutil
import signal as signal
import subprocess as sp
import sys as sys

# Open PDB file and read coordinates
pdb_file = open('align_z.pdb', 'r')
new_pdb_file = open('vac.pdb', 'w')



#Get last host atom
for num, line in enumerate(pdb_file, 1):
    if "L01" in line:
       print num
       break 


last_host=int(num)
print(last_host-1)

for atom in range(0, last_host-1):
    data = pdb_file.readline()
    new_pdb_file.write(data) 

【问题讨论】:

  • 更多 Pythonic last_host = next((num for num, line in enumerate(pdb_file, 1) if "L01" in line), len(list(pdb_file)))。为您节省 4 行代码。
  • 谢谢,但这并没有让我看到包含 L01 的第一行,而是最后一行。我需要找到第一行写着 L01
  • 不,应该可以。如果你得到最后一个没有包含"L01"的行。

标签: python for-loop enumerate


【解决方案1】:

一旦你通过enumerate 迭代pdf_file 你不能再次迭代它,除非调用pdb_file.seek(0) seek(0) 将流位置更改为开头

这是我的修改:

num = 1
for line in pdb_file:
    num += 1
    if "L01" in line:
       print num
       break 

pdb_file.seek(0)  # go back to the beginning and then it can be iterated again

last_host=int(num)
print(last_host-1)

for atom in range(0, last_host-1):
    data = pdb_file.readline()
    new_pdb_file.write(data) 

【讨论】:

  • 效果很好,非常感谢!你能解释一下“num超出范围”是什么意思吗?我对 python 完全陌生,不知道它是如何工作的......
  • @AndreasTosstorff 这是我的错。我以为num 是一个局部变量,只在for循环块中可见,这里有一个很好的解释mail.python.org/pipermail/python-ideas/2008-October/002109.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 2021-10-31
相关资源
最近更新 更多