turn list of letters into an array of integers
David Hutto
dwightdhutto at gmail.com
Wed Oct 24 01:50:38 EDT 2012
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 = [ ]
--
Best Regards,
David Hutto
CEO: http://www.hitwebdevelopment.com
More information about the Python-list
mailing list