-1

I am very new to Python. I have this list called 'prediction' with results from an LDA classification problem. The elements in 'prediction' are string, which I want to convert to numeric values. I am doing it by brute-force like:

aux2 = [0]*len(prediction)
i = 0
for k in prediction:
if k == 'ALA':
    aux2[i] = 1
elif k == 'ARG':
    aux2[i] = 2
elif k == 'ASN':
    aux2[i] = 3
elif k == 'ASP':
    aux2[i] = 4
...
elif k == 'VAL':
    aux2[i] = 18
i = i+1

But I am sure there is a better way to do it. Please put me out of my ignorance!

Gugumatz
  • 3
  • 1
  • 1
    is it important which numeric value a string gets, or is any unique value ok? e.g. must `'ASP'` get `4` exactly, or could it be `3` or `5`? – timgeb Feb 16 '22 at 10:09
  • 1
    @timgeb it would be best if numeric values are given as in the example: ascending alphabetically. So 'ALA'=1, 'ARG'=2 and so on. – Gugumatz Feb 16 '22 at 12:53

1 Answers1

0

You could use a dictionary for this! Dictionaries use keys to refer to certain values; This means you can assign each string an integer value according to your need and use it as so:

translation_dict = {
    'ALA': 1,
    'ARG': 2,
    'ASN': 3,
    'ASP': 4,
    ...
    'VAL': 18
}

aux2 = [0]*len(prediction)
for i, k in enumerate(prediction):
    aux2[i] = translation_dict[k]

You'll also notices I swapped out your counter (i) with an enumerate function. This function takes any iterator and returns a new iterator which gives you the index in addition to the value, thus saving you from manually incrementing i.

Adid
  • 1,504
  • 3
  • 13
  • Thanks for your answer. I didn't know about dictionaries! Next step is to make the translation dictionary automatically. Because the entries on the dictionary will change every time I use my code. I might have less or more than 18 entries (string codes). I can quite easily create a list containing all the entries for each time I run my code. Could I use such list to create the dictionary automatically? – Gugumatz Feb 16 '22 at 13:03
  • Answering my own comment. Yes, it is possible to create a dictionary using 2 lists. – Gugumatz Feb 16 '22 at 16:08