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!
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]
或者您可以使用map
:
map(RNA_dictionary.get, RNA_list)
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]
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.