Le mercredi 24 octobre 2012 07:23:11 UTC+2, seektime a écrit*:

> 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/0...s-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
Not so sure what you mean by an "array of integers".

>>> def z(s):
.... a = s.splitlines()

.... b = [e.split() for e in a]

.... for row in range(len(b)):

.... for col in range(len(b[row])):

.... b[row][col] = ord(b[row][col]) - ord('a')

.... return b

....

>>> z('a b a\n b b a')
[[0, 1, 0], [1, 1, 0]]

>>>

>>> # or

>>> table = {'a': 111, 'b': 222}

>>>

>>> def z2(s, table):
.... a = s.splitlines()

.... b = [e.split() for e in a]

.... for row in range(len(b)):

.... for col in range(len(b[row])):

.... b[row][col] = table[b[row][col]]

.... return b

....

>>> z2('a b a\n b b a', table)
[[111, 222, 111], [222, 222, 111]]

>>>

>>> # note

>>> z('a\n b b b b b\n a a')
[[0], [1, 1, 1, 1, 1], [0, 0]]

jmf