简体   繁体   中英

python 3, how to fix the frequency of occurrence

I would like to write a function named "frequency" which can fix the frequency of pairs in the second half of my output, for example if I fix the frequency of the couple ['A', 'C'] at 0,5 and the frequency of the couple ['M', 'K'] at 0,5, I would like an output like following:

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

I would like to change easily the value of the frequency I set. I tried to build a Function for this purpose, but I just could count the frequency of the existing couples, without fixing them.

the code I have is the following:

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)

where:

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())

it gives me an output like this:

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

thank you very much for any assistance!

I tried my best to understand what you meant. And let's see if the following does what you want:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM