turn list of letters into an array of integers

Prasad, Ramit ramit.prasad at jpmorgan.com
Thu Oct 25 17:27:16 EDT 2012


David Hutto wrote:
> On Wed, Oct 24, 2012 at 1:23 AM, seektime <michael.j.krause at gmail.com> wrote:
> > 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://gommeitputor.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'
> >
> I'd suggest, if this is what you're referring to:
> 
> x = seq.split('\n  ')
> array_list = [ ]
> next_3_d_array = []
> range_of_seq = len(seq)
> for num in range(0,range_of_seq):
>        if num % 3 != 0:
>                next_3_d_array.append(num)
>        if num % 3 == 0:
>                    array_list.append(next_3_d_array)
>                    next_3_d_array = [ ]
> 

Wow, that looks complicated. Why hardcode to 3 instead of where ever
the newline is?

>>> [ int(x.strip()) for subseq in seq.split('\n') for x in subseq.split() ]
[1, 2, 1, 2, 2, 1]
>>> lst = []
# OR
>>> for subseq in seq.split('\n'):
...     for x in subseq.split():
...         lst.append( int(x.strip()))
...     
>>>

Ramit Prasad


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  



More information about the Python-list mailing list