turn list of letters into an array of integers

seektime michael.j.krause at gmail.com
Wed Oct 24 01:23:11 EDT 2012


Here's some example code. The input is a list which is a "matrix" of letters:
   a  b  a
   b  b  a

and I'd like to turn this into a Python array:

  1 2 1
  2 2 1

so 1 replaces a, and 2 replaces b. Here's the code I have so far:

>>> L=['a b a\n','b b a\n']
>>> s=' '.join(L)
>>> seq1=('a','b')
>>> seq2=('1','2')
>>> d = dict(zip(seq1,seq2))
>>> # Define method to replace letters according to dictionary (got this from http://gomputor.wordpress.com/2008/09/27/search-replace-multiple-words-or-characters-with-python/).
... def replace_all(text, dic):
...     for i, j in dic.iteritems():
...         text = text.replace(i, j)
...     return text
... 

>>> seq = replace_all(s,d)
>>> print seq
1 2 1
 2 2 1

>>> seq
'1 2 1\n 2 2 1\n'

My question is how can I turn "seq" into a python array?

Thanks
Michael



More information about the Python-list mailing list