turn list of letters into an array of integers

S

seektime

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
....
1 2 1
2 2 1
'1 2 1\n 2 2 1\n'

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

Thanks
Michael
 
D

David Hutto

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/2...ace-multiple-words-or-characters-with-python/).
... def replace_all(text, dic):
... for i, j in dic.iteritems():
... text = text.replace(i, j)
... return text
...
1 2 1
2 2 1
'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 = [ ]
 
D

Demian Brecht

Of course, if you want these to be ints, then you can either change the format of your int list, or map(int, list_) if you don't have control over it.


Ugh, I'm tired. Shouldn't map it, the conversion should be done in the list comprehension to avoid a needless second list iteration.

K, I'm going to sleep now. :p

Demian Brecht
@demianbrecht
http://demianbrecht.github.com
 
C

Chris Rebert

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:

You mean a Python list. The datatype Python calls an `array` is very
different and relatively uncommonly used.
Although, confusingly, Python's lists are implemented using C arrays
rather than linked lists.
1 2 1
2 2 1

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

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

I'd say you're asking the wrong question. The better question is "Why
wasn't the result a list in the first place?". Many transformations
are cumbersome to express over just strings, which is why the first
job of most programs is to parse their input into a more convenient
structure that is suited to their main task(s).

This (along with some other improvements) leads to a better, somewhat
different program/algorithm:

letter2number = {'a': 1, 'b': 2}
with open("path/to/file.txt", "r") as f:
result = [[letter2number[letter] for letter in
line.strip().split()] for line in f]

If it's safe to assume that the correspondence between the letters and
numbers isn't completely arbitrary, some further improvements are also
possible.

Some relevant docs:
http://docs.python.org/library/stdtypes.html#string-methods
http://docs.python.org/tutorial/datastructures.html#list-comprehensions

Cheers,
Chris

P.S.: I'm guessing you obtained `L` from file.readlines() or similar;
it is worth noting for future reference that the readlines() method is
considered somewhat deprecated.
 
P

Peter Otten

Chris said:
line.strip().split()

No need to strip() if you are going to split on whitespace:
True

Lest the new idiom takes on while you are bravely fighting the immortable
readlines() ;)
 
8

88888 Dihedral

Chris Rebertæ–¼ 2012å¹´10月24日星期三UTC+8下åˆ2時07分29秒寫é“:
You mean a Python list. The datatype Python calls an `array` is very

different and relatively uncommonly used.

Although, confusingly, Python's lists are implemented using C arrays

rather than linked lists.

The list in python is a list of valid python objects.
For the number crunching part, please use arrays in numarray and scipy.
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']

'1 2 1\n 2 2 1\n'
My question is how can I turn "seq" into a python array?



I'd say you're asking the wrong question. The better question is "Why

wasn't the result a list in the first place?". Many transformations

are cumbersome to express over just strings, which is why the first

job of most programs is to parse their input into a more convenient

structure that is suited to their main task(s).



This (along with some other improvements) leads to a better, somewhat

different program/algorithm:



letter2number = {'a': 1, 'b': 2}

with open("path/to/file.txt", "r") as f:

result = [[letter2number[letter] for letter in

line.strip().split()] for line in f]



If it's safe to assume that the correspondence between the letters and

numbers isn't completely arbitrary, some further improvements are also

possible.



Some relevant docs:

http://docs.python.org/library/stdtypes.html#string-methods

http://docs.python.org/tutorial/datastructures.html#list-comprehensions



Cheers,

Chris



P.S.: I'm guessing you obtained `L` from file.readlines() or similar;

it is worth noting for future reference that the readlines() method is

considered somewhat deprecated.
 
8

88888 Dihedral

Chris Rebertæ–¼ 2012å¹´10月24日星期三UTC+8下åˆ2時07分29秒寫é“:
You mean a Python list. The datatype Python calls an `array` is very

different and relatively uncommonly used.

Although, confusingly, Python's lists are implemented using C arrays

rather than linked lists.

The list in python is a list of valid python objects.
For the number crunching part, please use arrays in numarray and scipy.
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']

'1 2 1\n 2 2 1\n'
My question is how can I turn "seq" into a python array?



I'd say you're asking the wrong question. The better question is "Why

wasn't the result a list in the first place?". Many transformations

are cumbersome to express over just strings, which is why the first

job of most programs is to parse their input into a more convenient

structure that is suited to their main task(s).



This (along with some other improvements) leads to a better, somewhat

different program/algorithm:



letter2number = {'a': 1, 'b': 2}

with open("path/to/file.txt", "r") as f:

result = [[letter2number[letter] for letter in

line.strip().split()] for line in f]



If it's safe to assume that the correspondence between the letters and

numbers isn't completely arbitrary, some further improvements are also

possible.



Some relevant docs:

http://docs.python.org/library/stdtypes.html#string-methods

http://docs.python.org/tutorial/datastructures.html#list-comprehensions



Cheers,

Chris



P.S.: I'm guessing you obtained `L` from file.readlines() or similar;

it is worth noting for future reference that the readlines() method is

considered somewhat deprecated.
 
R

Robert Kern

The list in python is a list of valid python objects.
For the number crunching part, please use arrays in numarray and scipy.

Your bot's database is laughably out of date.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
T

Terry Reedy

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.

If you are going to replace single characters (letters) with single
characters (digits), use maketrans and translate.
'1 2 3'
 
M

MRAB

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:

You mean a Python list. The datatype Python calls an `array` is very
different and relatively uncommonly used.
Although, confusingly, Python's lists are implemented using C arrays
rather than linked lists.
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']
'1 2 1\n 2 2 1\n'

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

I'd say you're asking the wrong question. The better question is "Why
wasn't the result a list in the first place?". Many transformations
are cumbersome to express over just strings, which is why the first
job of most programs is to parse their input into a more convenient
structure that is suited to their main task(s).

This (along with some other improvements) leads to a better, somewhat
different program/algorithm:

letter2number = {'a': 1, 'b': 2}
with open("path/to/file.txt", "r") as f:
result = [[letter2number[letter] for letter in line.strip().split()] for line in f]
If you're using .split() then you don't need to use .strip() as well:

result = [[letter2number[letter] for letter in line.split()] for
line in f]
 
W

wxjmfauth

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/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

...



1 2 1

2 2 1



'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".
.... 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
 
S

seektime

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

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



You mean a Python list. The datatype Python calls an `array` is very

different and relatively uncommonly used.

Although, confusingly, Python's lists are implemented using C arrays

rather than linked lists.


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']

'1 2 1\n 2 2 1\n'
My question is how can I turn "seq" into a python array?



I'd say you're asking the wrong question. The better question is "Why

wasn't the result a list in the first place?". Many transformations

are cumbersome to express over just strings, which is why the first

job of most programs is to parse their input into a more convenient

structure that is suited to their main task(s).



This (along with some other improvements) leads to a better, somewhat

different program/algorithm:



letter2number = {'a': 1, 'b': 2}

with open("path/to/file.txt", "r") as f:

result = [[letter2number[letter] for letter in

line.strip().split()] for line in f]



If it's safe to assume that the correspondence between the letters and

numbers isn't completely arbitrary, some further improvements are also

possible.



Some relevant docs:

http://docs.python.org/library/stdtypes.html#string-methods

http://docs.python.org/tutorial/datastructures.html#list-comprehensions



Cheers,

Chris



P.S.: I'm guessing you obtained `L` from file.readlines() or similar;

it is worth noting for future reference that the readlines() method is

considered somewhat deprecated.

Thanks to everyone lots of great comments are actionable suggestions.

My intension is to used the numpy/scipy packages to solve the task at hand.I agree that there's no point in loading a file into a format which only needs to be converted right after loading. But I'm new to Python the f.readline(s) command, according to the 2.7.3 tutorial and manual, is pretty much all there is for file i/o. If, as you indicated, f.readlines() is deprecated then what should I use instead? I'm using ver. 2.6 on Linux (it's a bit dated, I know).
 
S

seektime

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

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



You mean a Python list. The datatype Python calls an `array` is very

different and relatively uncommonly used.

Although, confusingly, Python's lists are implemented using C arrays

rather than linked lists.


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']

'1 2 1\n 2 2 1\n'
My question is how can I turn "seq" into a python array?



I'd say you're asking the wrong question. The better question is "Why

wasn't the result a list in the first place?". Many transformations

are cumbersome to express over just strings, which is why the first

job of most programs is to parse their input into a more convenient

structure that is suited to their main task(s).



This (along with some other improvements) leads to a better, somewhat

different program/algorithm:



letter2number = {'a': 1, 'b': 2}

with open("path/to/file.txt", "r") as f:

result = [[letter2number[letter] for letter in

line.strip().split()] for line in f]



If it's safe to assume that the correspondence between the letters and

numbers isn't completely arbitrary, some further improvements are also

possible.



Some relevant docs:

http://docs.python.org/library/stdtypes.html#string-methods

http://docs.python.org/tutorial/datastructures.html#list-comprehensions



Cheers,

Chris



P.S.: I'm guessing you obtained `L` from file.readlines() or similar;

it is worth noting for future reference that the readlines() method is

considered somewhat deprecated.

Thanks to everyone lots of great comments are actionable suggestions.

My intension is to used the numpy/scipy packages to solve the task at hand.I agree that there's no point in loading a file into a format which only needs to be converted right after loading. But I'm new to Python the f.readline(s) command, according to the 2.7.3 tutorial and manual, is pretty much all there is for file i/o. If, as you indicated, f.readlines() is deprecated then what should I use instead? I'm using ver. 2.6 on Linux (it's a bit dated, I know).
 
C

Chris Rebert

Thanks to everyone lots of great comments are actionable suggestions.

My intension is to used the numpy/scipy packages to solve the task at hand. I agree that there's no point in loading a file into a format which onlyneeds to be converted right after loading. But I'm new to Python the f.readline(s) command, according to the 2.7.3 tutorial and manual, is pretty much all there is for file i/o. If, as you indicated, f.readlines() is deprecated then what should I use instead? I'm using ver. 2.6 on Linux (it's a bitdated, I know).

Just iterate over the file directly using a for-loop (e.g. `for line
in some_file:`). Each iteration yields one line of the file. I used a
very minor variation of this approach in my code (a list comprehension
is just syntax sugar for a for-loop).

Cheers,
Chris
 
P

Peter Otten

Dennis said:
Readlines() isn't immortal... It's a lich
http://en.wikipedia.org/wiki/Lich

Wasn't there a Monty Python sketch where a man carrying a parrot in a cage
comes into a shop full of stuffed animals and complains: No, I don't admire
the taxidermist for making that parrot look like it were alive -- that beast
bit me!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top