python 3,如何修复发生的频率

时间:2015-03-19 14:59:11

标签: python function python-3.x word-frequency

我想编写一个名为“frequency”的函数,可以在输出的后半部分修复对的频率,例如,如果我将对的频率['A','C']固定为0 ,5和夫妇['M','K']在0,5的频率,我想输出如下:

['A', 'K']
    ['A', 'K']
    ['A', 'K']
    ['A', 'K']
    ['A', 'K']
    ['A', 'C']
    ['A', 'C']
    ['A', 'C']
    ['M', 'K']
    ['M', 'K']
    ['M', 'K']

我想轻易改变我设定的频率值。我试图为此目的构建一个函数,但我可以计算现有耦合的频率,而无需修复它们。

我的代码如下:

for i in range(int(lengthPairs/2)):
    pairs.append([aminoacids[0], aminoacids[11]])
print(int(lengthPairs/2))

for j in range(int(lengthPairs/2)+1):
    dictionary = dict()
    r1 = randrange(20)
    r2 = randrange(20)
    pairs.append([aminoacids[r1], aminoacids[r2]])

for pair in pairs:
    print (pair)

其中:

aminoacids = ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V']
lengthPairs = 10
pairs = list(list())

它给我一个这样的输出:

['A', 'K']
['A', 'K']
['A', 'K']
['A', 'K']
['A', 'K']
['A', 'C']
['M', 'K']
['I', 'I']
['F', 'G']
['V', 'H']
['V', 'I']

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我尽力了解你的意思。让我们看看以下是否符合您的要求:

aminoacids = ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V']

pair_fq_change = [aminoacids[0], aminoacids[11]] #the pair that you'd like to change the frequency, e.g. ['A', 'K']

original_pairs = [['D', 'E'], ['S', 'F'], ['A', 'K'], ['A', 'K'], ['A', 'K'], ['A', 'K'], ['A', 'K'], ['B', 'C']]


def frequency(original_pairs, pair_fq_change, fq):
'''fq is the number of frequency that you want the pair_fq_change to have'''
    updated_pairs = []
    count = 0
    for pair in original_pairs:
        if pair != pair_fq_change:
            updated_pairs.append(pair)
        elif pair == pair_fq_change and count < fq:
            updated_pairs.append(pair)
            count += 1
        else:
            continue
    return updated_pairs        

updated_pairs = frequency(original_pairs, pair_fq_change, 3)
print(updated_pairs)

>>>[['D', 'E'], ['S', 'F'], ['A', 'K'], ['A', 'K'], ['A', 'K'], ['B', 'C']]