python 3,如何修正发生频率

2024-06-02 06:50:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个名为“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']

非常感谢您的帮助!你知道吗


Tags: 函数inforrangeint频率r2print
1条回答
网友
1楼 · 发布于 2024-06-02 06:50:48

我尽力去理解你的意思。让我们看看下面的内容是否符合您的要求:

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']]

相关问题 更多 >