Py学习  »  Python

python 3中打印next()的问题

Fernanda Costa • 7 年前 • 2061 次点击  

我对python 3中的命令print(next())有一个奇怪的问题。

当我使用它在控制台上打印时,它工作得很好,但是当我试图将输出保存到文件中时,它就不工作了! 我使用的命令如下:

for item in final:
    fasta = open(fname) # fname is the name if input file
    for line in fasta:
        line = line.strip()
        if item in line:
            item = item.strip()
            print('Line:', line, '\nNext line:', next(fasta)) # this works perfectly!
            print(line, next(fasta), file=open('finalList.fa', "a")) # this one doesn't work!

最后一个命令的输出 下一步(FASTA) 部分是 线+ 2 而不是 线+ 1 ,就像我从print-on-console命令中得到的一样。

有人知道发生了什么事吗?任何小费都将不胜感激!

提前谢谢大家。

热忱地,

费尔南达·科斯塔

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/42934
文章 [ 3 ]  |  最新文章 7 年前
Fernanda Costa
Reply   •   1 楼
Fernanda Costa    7 年前

我刚意识到你打电话的时候 下() python 3 it中的命令 正确读取第+1行,当我再次调用它时,它将考虑下一行而不是第二行,因此它将打印下一行,即第+2行!

所以我在控制台命令行中删除了打印内容。

谢谢大家,对noob问题表示抱歉!

Younes
Reply   •   2 楼
Younes    7 年前

您是否试图创建一个变量并在该变量中传递next(foo)的值,最后打印该变量?

Carcigenicate
Reply   •   3 楼
Carcigenicate    7 年前

Calling next advances the given iterator ( fasta 在这种情况下)。多次调用它将多次前进并导致跳过元素。如果要在不同的位置使用数据,则需要将返回值保存在变量中:

if item in line:
    data = next(fasta) # Save it here
    item = item.strip()
    print('Line:', line, '\nNext line:', data) # Then use it multiple times here and below
    print(line, data, file=open('finalList.fa', "a"))