Change value of portion of a string within a list get sum of string

Viewed 30

I am working on using itertools to get a list of combinations, but am stuck with manipulating those combinations once I have them. Here is what I have:

k_instances = 3 #Instances of lysine
k_modifications = {'Hydroxylation', 'Carboxylation', #Modifications applicable to lysine
                   }

k_combinations = itertools.combinations_with_replacement(k_modifications, k_instances) #Possible modifications assigned

k_comb_list = list(k_combinations) #Convert combinations to a list

k_comb_list_str = [k_comb_list[i:i+k_instances] for i in range(0, len(k_comb_list), k_instances)]

for i in range(len(k_comb_list_str)):
    k_comb_list_str[i] = 16 if k_comb_list_str[i] == 'Hydroxylation' else k_comb_list_str[i]
 
    print(k_comb_list_str)

When running this, I get:

 [[('Carboxylation', 'Carboxylation', 'Carboxylation'), ('Carboxylation', 'Carboxylation', 'Hydroxylation'), ('Carboxylation', 'Hydroxylation', 'Hydroxylation')], [('Hydroxylation', 'Hydroxylation', 'Hydroxylation')]]

My idea is to replace each of these variables with their mass, for instance replace all occurrences of Carboxylation with 16. Doing this I would like to end up with a list of strings, something like this:

[[(16,16,16),(16,16,2),(16,2,2)...]]

I would then get the sum of each of the strings:

[[(48),(32),(20)]]

And then essentially have a list of values possible based on the combinations.

I'm sure there is a simpler way about carrying this out, so any suggestions for how to execute this would be appreciated. I have tried replacing each value using else if statements, but it doesn't work because I can't figure out how to manipulate within the string, so I can only search for the string, which defeats the purpose.

1 Answers

The easiest option is to make the various molecules variables, and use those, rather than trying to do string replacement later. For example:

import itertools

Hydroxylation = 2
Carboxylation = 16

k_instances = 3
k_modifications = [Hydroxylation, Carboxylation]

k_combinations = itertools.combinations_with_replacement(k_modifications, k_instances)

k_comb_l = list(k_combinations)
print(k_comb_l)
# [(16, 16, 16), (16, 16, 2), (16, 2, 2), (2, 2, 2)]
print([sum(x) for x in k_comb_l])
# [48, 34, 20, 6]
Related