Storing a set of integers in a list

I have a list containing the basic letters of RNA and a dictionary for converting them to numerical values. What I'm trying to do is save these numeric values ​​to 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 are 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 this leads to an error because the for loop cannot iterate over integers. I am new to Python, so I don’t know how to approach this. If anyone else can help me, I would really appreciate it!

+4
source share
4 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

Exit

[3, 4, 1, 2]

Or using list comprehension

RNA_integers = [RNA_dictionary[i] for i in RNA_list if i in RNA_dictionary]
+5

map:

map(RNA_dictionary.get, RNA_list)

+3

:

RNA_dictionary.values()

[1, 3, 2, 4]

EDIT . If you need to store the values ​​in the same order as RNA_list, you can use list comprehension like thefourtheye :

RNA_integers = [RNA_dictionary[i] for i in RNA_list if i in RNA_dictionary]
+1
source

Try it,

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

print RNA_integers

out put will

[3,4,1,2]
0
source

All Articles