簡體   English   中英

For 循環僅打印 Python 中的最后一個值

[英]For loop prints only last value in Python

我是編程新手,我學習 Python 的時間很短。 下面,我嘗試編寫一個代碼,計算樣本 DNA 序列中的核苷酸(來自 ROSALIND 的問題)。

nucleotides=['A','C','G','T']

string='AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'

    for n in nucleotides:

        a = string.count (n)

        print ("The count for",n,"is:",a)

輸出是:

The count for T is: 21

問題是我的代碼只打印“核苷酸”數組中最后一個元素的結果,即“T”。 我知道我在問一個愚蠢的問題,但我試圖通過在此處和網絡上搜索來找到答案,但沒有成功。 這就是為什么,如果您能更正代碼並向我解釋為什么我的循環沒有打印每個核苷酸的計數,我將不勝感激。

非常感謝!

我會檢查您代碼中的縮進,因為它在您的問題中不正確。 這個片段應該工作。

nucleotides=['A','C','G','T']

string='AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'

for n in nucleotides:
    a = string.count (n)
    print ("The count for",n,"is:",a)

正如其他答案所指出的,您的問題是縮進。

或者,您可以使用Counter from collections來獲取包含每個字母出現頻率的字典。 然后循環你的nucleotides來打印頻率。

from collections import Counter

nucleotides=['A','C','G','T']
string='AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'
counts = Counter(string)

for n in nucleotides:
    a = counts[n]
    print ("The count for",n,"is:",a)

輸出

The count for A is: 20
The count for C is: 12
The count for G is: 17
The count for T is: 21

您的代碼實際上可以正常工作,除了您在 for 循環中添加了一個額外的制表符(錯誤的縮進)。 你可以試試這個稍微改進的變化:

# define nucleotides 
nucleotides=['A','C','G','T']
# define dna chain
string='AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'

# iterate through the dna chain and count 
# the number of appearances for each nucelotide.
for nucl in nucleotides:
    x = string.count(nucl)
    print ("The count for " + nucl + " is: " + str(x))

我在 sublime 上嘗試了代碼並得到了以下結果。

('The count for', 'A', 'is:', 20)
('The count for', 'C', 'is:', 12)
('The count for', 'G', 'is:', 17)
('The count for', 'T', 'is:', 21)

我認為您的代碼的問題在於您不必要地縮進了“for 循環”。 確保使用正確的縮進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM