python 3 中打印 next() 的问题

issues in printing next() in python 3

我在 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!

我从上一个命令的 next(fasta) 部分得到的输出是 line+2 而不是 line+1,就像我从 print on console 命令中得到的那样。

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

提前谢谢大家。

亲切地,

费尔南达·科斯塔

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

Calling next advances the given iterator(在本例中为 fasta)。多次调用它会多次推进并导致元素被跳过。如果要在不同的地方使用数据,则需要将 return 值保存在变量中:

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"))

我刚刚意识到,当您在 python 3 中调用 next() 命令时,它 正确读取第 1 行,当我再次调用它时, 它会考虑 line the next(line) 而不是 line, 所以它打印 next(next(line) 这是 line+2!

所以我通过删除控制台命令行中的打印来修复它。

谢谢大家,对于菜鸟问题​​,我们深表歉意!