Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a collection of integers in a list

I have a list containing RNA base letters and a dictionary to convert them to numeric values. What I am trying to do is store these numeric values into a new list. I have:

RNA_list = ['C', 'G', 'A', 'U']
RNA_dictionary = {'A': 1, 'U': 2, 'C': 3, 'G': 4}
for i in RNA_list:
    if i in RNA_dictionary:
        RNA_integers = RNA_dictionary[i]
    else:
        print()

So RNA_integers is 3, 4, 1, 2, but I need to store them in a list somehow. I wanted to do something like:

RNA_integer_list = []
for i in RNA_integers:
    RNA_integer_list = RNA_integer_list + i

But that results in an error because the for loop can't iterate over the integers. I'm new to Python so I'm not sure how to approach this. If anyone else can help me, I'd really appreciate it!

like image 295
kindrex735 Avatar asked Jan 12 '23 01:01

kindrex735


2 Answers

You can do

RNA_list = ['C', 'G', 'A', 'U']
RNA_dictionary = {'A': 1, 'U': 2, 'C': 3, 'G': 4}
RNA_integers = []
for i in RNA_list:
    if i in RNA_dictionary:
        RNA_integers.append (RNA_dictionary[i])

print RNA_integers

Output

[3, 4, 1, 2]

Or using list comprehension

RNA_integers = [RNA_dictionary[i] for i in RNA_list if i in RNA_dictionary]
like image 199
thefourtheye Avatar answered Jan 20 '23 04:01

thefourtheye


Or you can use map:

map(RNA_dictionary.get, RNA_list)

like image 44
satoru Avatar answered Jan 20 '23 02:01

satoru