【问题标题】:For loop prints only last value in PythonFor 循环仅打印 Python 中的最后一个值
【发布时间】:2018-12-23 17:44:26
【问题描述】:

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

非常感谢!

【问题讨论】:

  • Python 对缩进很敏感。确保 print 语句相对于 for 语句缩进。
  • 这里的缩进和你代码中的缩进匹配吗?我怀疑你的代码在 for 循环之外有 print 语句,但在这里看起来不是这样。
  • 以下任何答案是否能解决您的问题?如果他们这样做,则将您找到的最佳答案标记为已接受。由于您似乎是 Stack Overflow 的新手,您应该阅读What should I do when someone answers my question?

标签: python python-3.x


【解决方案1】:

我会检查您代码中的缩进,因为它在您的问题中不正确。这个 sn-p 应该可以工作。

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

string='AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'

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

【讨论】:

    【解决方案2】:

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

    或者,您可以使用Counter 中的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
    

    【讨论】:

      【解决方案3】:

      您的代码实际上正在运行,除了您在 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))
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-07-28
          • 2022-01-24
          • 1970-01-01
          • 1970-01-01
          • 2022-06-15
          • 2022-01-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多