首页 > 解决方案 > 我怎样才能重写这个给我一个答案列表?

问题描述

我是python和编程的新手,任何帮助将不胜感激!我在用 Python 编写的一段代码时遇到了问题。我的任务是编写一个函数来计算特定字母出现的次数除以该序列中的字母总数。
我的函数应该返回一个列表,其中包含每个序列的字母分数。

def calculate_let(sequences, letter):
    calculate_letNew = []
    for seq in sequences:
        len(seq)
        calculate_letNew = seq.count(letter)/len(seq)
    return calculate_letNew

到目前为止,这是我的代码。输出只给了我一个序列的一小部分,即使列表sequenceA有四个序列也是如此。

Letter_A = calculate_let(sequenceA, 'A')
print(Letter_A)

输出:0.10273972602739725

我一直在尽最大努力尝试解决这个问题,但老实说,我不知道从哪里开始。

标签: python

解决方案


我认为您打算像这样列出它们:

请注意,该list.append方法会将一个元素添加到列表中。

def count_lett(sequences, AminoAcid):
    count_lettNew = []
    for seq in sequences:
        count_lettNew.append(seq.count(AminoAcid)/len(seq))
    return count_lettNew

作为随机建议:

Python 只使用 TitleCase 作为类名,所以我会选择这样编写代码(forloop为简单起见保留):

def count_lett(sequences, amino_acid):
    counts = [] # Although, you may consider something like fracs 
                # for "fractions" since these aren't actually counts
    for seq in sequences:
        counts.append(seq.count(amino_acid)/len(seq))
    return counts

推荐阅读