简体   繁体   English

如何更改打印以在python中的for循环中返回?

[英]How do I change print to return in a for loop in python?

The following code is doing most of what I want... 以下代码可以满足我的大部分需求...

All I need is for that print to actually be a return so that I can dump the data into another txt file I'm writing ( f2 ). 我只需要将该print实际return以便可以将数据转储到我正在写入的另一个txt文件中( f2 )。

(Also, the spacing obtained with print letters is not what I want but I figure I'll deal with it later.) (此外,通过print letters获得的间距不是我想要的,但我认为稍后会处理。)

Every time I replace print with return it just stops reading after the first line of the initial text file ( f1 ). 每次我用return替换print ,它都会在初始文本文件( f1 )的第一行之后停止读取。

def DNA2Prot(f1, f2="translated_fasta.txt"):
    fin = open(f1, 'r')
    for letters in fin:
        if letters[0] != ">":
            seqs = letters
            codons = [ ]
            protein = ''
            for i in range(0, len(seqs), 3):
                try:
                    codon = seqs[i:i+3]
                    codons = codon_table[codon]
                    protein = protein+codons
                except KeyError:
                    protein += ""
            print protein
        else:
            print letters
    fin.close()

Use yield instead and treat your function as a generator. 请改用yield并将函数用作生成器。 This way the caller can do what he/she pleases with all of the proteins the DNA2Prot function generates and read from the file until the entire file is read. 这样,调用者就可以使用DNA2Prot函数生成并从文件读取的所有蛋白质来完成他/她喜欢的事情,直到读取整个文件为止。

def DNA2Prot(f1, f2='translated_fasta.txt'):
    # prefer using `with` to `open` and `close`
    with open(f1, 'r') as fin:
        for letters in fin: 
            if letters[0] != '>':
                seqs = letters
                codons = [ ]
                protein = ''
                for i in range(0, len(seqs), 3):
                    # no need for a try catch, because we can use `get`
                    # get will return None by default if the 
                    # specified `codon` does not appear in 
                    # `codon_table`
                    codon = seqs[i:i + 3]       
                    codons = codon_table.get(codon)
                    if codons:
                        protein += codons
                yield protein
            else:
                yield letters        

Now you have to treat the DNA2Prot function as an Iterator : 现在,您必须将DNA2Prot函数视为Iterator

with open('/path/to/outfile', 'w') as f:
    for protein in DNA2Prot(f1):
        # do something with protein
        print protein

First things first. 首先是第一件事。 When you use the return statement you are telling your code to break out(ie leave) from the point where the return statement is located. 当您使用return语句时,您正在告诉您的代码从return语句所在的位置中断(即离开)。 This means that your code will start reading from fin, move on to the second for and as soon as it is done with it (read all the letters of the line) it will reach you return statement and break out from the DNA2prot function. 这意味着您的代码将开始从fin读取,然后移至第二个,并且一旦完成操作(读取该行的所有字母),它将到达您的return语句并脱离DNA2prot函数。

Now, there are two things you can do to when it comes to files. 现在,涉及文件时您可以做两件事。 First is use the print function to redirect your output to a file (not recommended) or properly open the files and write into them. 首先是使用打印功能将输出重定向到文件(不建议)或正确打开文件并写入文件。

With regards to the first solution (and assuming you are using python 2.7) you can simply do: 关于第一个解决方案(并假设您使用的是python 2.7),您可以简单地执行以下操作:

from __future__ import print_function

and when you want to use your print statement just write: 当您想使用打印语句时,只需写:

print(protein, file = fin).

However, if I were you I would go for a more elegant and clean solution that doesn't rely on unnecessary imports: 但是,如果您是我,我将寻求一种不依赖不必要的导入的更优雅,更干净的解决方案:

def DNA2Prot(f1, f2="translated_fasta.txt"):
with open (f1, 'r+') as fin, open(f2, 'w+') as fin2: #Using the "with-open" statement you don't need to close the file object
    for letters in fin:
        if letters[0]!=">":
            seqs=letters
            codons=[ ]
            protein=''
            for i in range(0,len(seqs),3):
                try:
                    codon=seqs[i:i+3]
                    codons=codon_table[codon]
                    protein=protein+codons
                except KeyError:
                     protein+=""
            f2.write(protein) # Write your data to the second file             

        else:
            f2.write(letters) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM