Translate a list of multiple words into a list of multiple numbers using a dictionary in Python(2.7.1)
I have a code "aaabbbcccdddeee"
that I split up into 3 letter words (such as 'aaa'
,'bbb'
,'ccc'
. . . and so on) and assigned a number value to them using d=dict(zip(('aaa','bbb','ccc','ddd','eee'),(123,234,345,456,567)))
If I have a random sequence of 3 letter words
RANDOM="'aaa','bbb','ddd','ccc','eee','ddd','bbb','aaa','eee','ccc'"
How can I create a list that converts the RANDOM list into a list composed of the number values that were assigned previously in the dictionary
Example: RANDOM="'aaa','bbb','ddd','ccc','eee','ddd',开发者_C百科'bbb','aaa','eee','ccc'"
' to produce '123','234','456','345','567','456','234','123','567','345'
I found out how to do it for 1 value:
>>> x=d['aaa']
>>> print x
>>> 123
How do I do it for the whole list of RANDOM? It does not work if i simply put:
>>> y=d['aaa','bbb','ddd','ccc',...]
Does anyone know why this won't work or how to get it to work to get the full list of numbers . i.e. 123,234,456,345,...?
I have been messing with this on and off for a few weeks. It's not homework if your wondering, but this can help me with my studies in other areas. Any help would be greatly appreciated!
Iterate.
y = [d[x] for x in L]
y = map(d.get, RANDOM)
Example:
>>> d = dict(zip(('aaa','bbb','ccc','ddd','eee'), (123,234,345,456,567)))
>>> RANDOM = ['aaa','bbb','ddd','ccc','eee','ddd','bbb','aaa','eee','ccc']
>>> y = map(d.get, RANDOM)
>>> y
[123, 234, 456, 345, 567, 456, 234, 123, 567, 345]
if RANDOM
contains an item that is not in d
then d.get()
returns None
instead of raising KeyError
in the middle of constructing the y
list.
y=d['aaa','bbb','ddd','ccc',...] won't work because 'aaa','bbb','ddd','ccc' is not a valid key. The y = d[ ... ] looks up a SINGLE key value, and returns the SINGLE matching entry for that key in the dictionary.
So, you just need to translate each entry one at a time.
y=d['aaa']
x=d['bbb']
z=d['ccc']
and then a = [y, x, z] ... etc.
or, being more intelligent, we can use a loop that loops based on the length of the RANDOM list.
a = list()
for x in RANDOM:
a.append(d[x])
or, to be fancy
a = [d[x] for x in RANDOM]
精彩评论