kindrex735
kindrex735

Reputation: 55

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!

Upvotes: 4

Views: 5255

Answers (4)

Ashif Abdulrahman
Ashif Abdulrahman

Reputation: 2137

You try this,

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 be

[3,4,1,2]

Upvotes: 0

satoru
satoru

Reputation: 33215

Or you can use map:

map(RNA_dictionary.get, RNA_list)

Upvotes: 3

dparpyani
dparpyani

Reputation: 2493

You can simply do:

RNA_dictionary.values()

to get [1, 3, 2, 4]

EDIT: If you need to keep the values in a similar order as RNA_list, you can use list comprehension as thefourtheye suggests:

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

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239453

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]

Upvotes: 5

Related Questions