簡體   English   中英

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

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

以下代碼可以滿足我的大部分需求...

我只需要將該print實際return以便可以將數據轉儲到我正在寫入的另一個txt文件中( f2 )。

(此外,通過print letters獲得的間距不是我想要的,但我認為稍后會處理。)

每次我用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()

請改用yield並將函數用作生成器。 這樣,調用者就可以使用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        

現在,您必須將DNA2Prot函數視為Iterator

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

首先是第一件事。 當您使用return語句時,您正在告訴您的代碼從return語句所在的位置中斷(即離開)。 這意味着您的代碼將開始從fin讀取,然后移至第二個,並且一旦完成操作(讀取該行的所有字母),它將到達您的return語句並脫離DNA2prot函數。

現在,涉及文件時您可以做兩件事。 首先是使用打印功能將輸出重定向到文件(不建議)或正確打開文件並寫入文件。

關於第一個解決方案(並假設您使用的是python 2.7),您可以簡單地執行以下操作:

from __future__ import print_function

當您想使用打印語句時,只需寫:

print(protein, file = fin).

但是,如果您是我,我將尋求一種不依賴不必要的導入的更優雅,更干凈的解決方案:

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