For循环仅打印Python中的最后一个值

时间:2018-12-23 17:44:26

标签: python python-3.x

我是编程的新手,并且学习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”。我知道我在问一个愚蠢的问题,但是我试图通过在此处和网络上搜索来找到答案,但是我没有成功。这就是为什么,如果您能更正代码并向我解释为什么我的循环不显示每个核苷酸的计数,我将不胜感激。

非常感谢!

4 个答案:

答案 0 :(得分:2)

我会检查您代码中的缩进,因为您的问题不正确。该代码段应该可以使用。

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

string='AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'

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

答案 1 :(得分:2)

您的问题是其他答案所指出的缩进。

或者,您可以使用collections中的Counter来获取包含每个字母出现频率的字典。然后,只需在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

答案 2 :(得分:0)

我尝试了崇高的代码,并得到了以下结果。

('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循环”。确保使用正确的缩进。

答案 3 :(得分:0)

您的代码实际上是有效的,除了您在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:
    a = string.count(nucl)
    print "The count for " + nucl + " is: " + str(a)
相关问题