Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #31991 > unrolled thread

turn list of letters into an array of integers

Started byseektime <michael.j.krause@gmail.com>
First post2012-10-23 22:23 -0700
Last post2012-10-25 21:27 +0000
Articles 20 on this page of 24 — 14 participants

Back to article view | Back to comp.lang.python


Contents

  turn list of letters into an array of integers seektime <michael.j.krause@gmail.com> - 2012-10-23 22:23 -0700
    Re: turn list of letters into an array of integers Demian Brecht <demianbrecht@gmail.com> - 2012-10-23 22:45 -0700
    Re: turn list of letters into an array of integers David Hutto <dwightdhutto@gmail.com> - 2012-10-24 01:50 -0400
    Re: turn list of letters into an array of integers Demian Brecht <demianbrecht@gmail.com> - 2012-10-23 22:51 -0700
    Re: turn list of letters into an array of integers Demian Brecht <demianbrecht@gmail.com> - 2012-10-23 22:54 -0700
    Re: turn list of letters into an array of integers Chris Rebert <clp2@rebertia.com> - 2012-10-23 23:07 -0700
      Re: turn list of letters into an array of integers 88888 Dihedral <dihedral88888@googlemail.com> - 2012-10-24 05:03 -0700
        Re: turn list of letters into an array of integers Robert Kern <robert.kern@gmail.com> - 2012-10-24 13:22 +0100
      Re: turn list of letters into an array of integers 88888 Dihedral <dihedral88888@googlemail.com> - 2012-10-24 05:03 -0700
      Re: turn list of letters into an array of integers seektime <michael.j.krause@gmail.com> - 2012-10-24 21:27 -0700
        Re: turn list of letters into an array of integers Chris Rebert <clp2@rebertia.com> - 2012-10-24 21:52 -0700
      Re: turn list of letters into an array of integers seektime <michael.j.krause@gmail.com> - 2012-10-24 21:27 -0700
    Re: turn list of letters into an array of integers Peter Otten <__peter__@web.de> - 2012-10-24 09:47 +0200
    Re: turn list of letters into an array of integers Peter Otten <__peter__@web.de> - 2012-10-24 11:04 +0200
    Re: turn list of letters into an array of integers Terry Reedy <tjreedy@udel.edu> - 2012-10-24 11:56 -0400
    Re: turn list of letters into an array of integers MRAB <python@mrabarnett.plus.com> - 2012-10-24 18:05 +0100
    Re: turn list of letters into an array of integers wxjmfauth@gmail.com - 2012-10-24 10:27 -0700
      Re: turn list of letters into an array of integers Demian Brecht <demianbrecht@gmail.com> - 2012-10-24 10:36 -0700
    Re: turn list of letters into an array of integers Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2012-10-24 15:57 -0400
    [OT] Re: turn list of letters into an array of integers Peter Otten <__peter__@web.de> - 2012-10-25 07:47 +0200
      Re: [OT] Re: turn list of letters into an array of integers Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-10-25 07:49 +0000
        Re: [OT] Re: turn list of letters into an array of integers Peter Otten <__peter__@web.de> - 2012-10-25 10:25 +0200
        Re: [OT] Re: turn list of letters into an array of integers Mark Lawrence <breamoreboy@yahoo.co.uk> - 2012-10-25 09:55 +0100
    RE: turn list of letters into an array of integers "Prasad, Ramit" <ramit.prasad@jpmorgan.com> - 2012-10-25 21:27 +0000

Page 1 of 2  [1] 2  Next page →


#31991 — turn list of letters into an array of integers

Fromseektime <michael.j.krause@gmail.com>
Date2012-10-23 22:23 -0700
Subjectturn list of letters into an array of integers
Message-ID<07073002-d79f-46f6-83fc-8d20c51b39c3@googlegroups.com>
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

[toc] | [next] | [standalone]


#31997

FromDemian Brecht <demianbrecht@gmail.com>
Date2012-10-23 22:45 -0700
Message-ID<mailman.2721.1351057518.27098.python-list@python.org>
In reply to#31991
On 2012-10-23, at 10:23 PM, seektime <michael.j.krause@gmail.com> wrote:
> My question is how can I turn "seq" into a python array?


Something like this perhaps?:

>>> alpha = ('a', 'b')
>>> numeric = ('1', '2')
>>> L = ['a b a\n', 'b b a\n']
>>> s = ' '.join(L)
>>> d = dict(zip(alpha, numeric))
>>> list_ = [d[c] for c in s.strip('\n').split()]
>>> list_
['1', '2', '1', '2', '2', '1']

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



[toc] | [prev] | [next] | [standalone]


#31999

FromDavid Hutto <dwightdhutto@gmail.com>
Date2012-10-24 01:50 -0400
Message-ID<mailman.2722.1351057840.27098.python-list@python.org>
In reply to#31991
On Wed, Oct 24, 2012 at 1:23 AM, seektime <michael.j.krause@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

[toc] | [prev] | [next] | [standalone]


#32000

FromDemian Brecht <demianbrecht@gmail.com>
Date2012-10-23 22:51 -0700
Message-ID<mailman.2723.1351057893.27098.python-list@python.org>
In reply to#31991
On 2012-10-23, at 10:45 PM, Demian Brecht <demianbrecht@gmail.com> wrote:

>>>> list_ = [d[c] for c in s.strip('\n').split()]
>>>> list_
> ['1', '2', '1', '2', '2', '1']


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.

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



[toc] | [prev] | [next] | [standalone]


#32001

FromDemian Brecht <demianbrecht@gmail.com>
Date2012-10-23 22:54 -0700
Message-ID<mailman.2724.1351058076.27098.python-list@python.org>
In reply to#31991
> 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



[toc] | [prev] | [next] | [standalone]


#32004

FromChris Rebert <clp2@rebertia.com>
Date2012-10-23 23:07 -0700
Message-ID<mailman.2727.1351058849.27098.python-list@python.org>
In reply to#31991
On Tue, Oct 23, 2012 at 10:23 PM, seektime <michael.j.krause@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:

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']
<snip>
>>>> seq
> '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.

[toc] | [prev] | [next] | [standalone]


#32028

From88888 Dihedral <dihedral88888@googlemail.com>
Date2012-10-24 05:03 -0700
Message-ID<72525506-d336-4181-8e90-56e092c29a2b@googlegroups.com>
In reply to#32004
Chris Rebert於 2012年10月24日星期三UTC+8下午2時07分29秒寫道:
> On Tue, Oct 23, 2012 at 10:23 PM, seektime <michael.j.krause@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:
> 
> 
> 
> 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. 

> 
> >   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']
> 
> <snip>
> 
> >>>> seq
> 
> > '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.

[toc] | [prev] | [next] | [standalone]


#32031

FromRobert Kern <robert.kern@gmail.com>
Date2012-10-24 13:22 +0100
Message-ID<mailman.2753.1351081349.27098.python-list@python.org>
In reply to#32028
On 10/24/12 1:03 PM, 88888 Dihedral wrote:

> 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

[toc] | [prev] | [next] | [standalone]


#32029

From88888 Dihedral <dihedral88888@googlemail.com>
Date2012-10-24 05:03 -0700
Message-ID<mailman.2750.1351080235.27098.python-list@python.org>
In reply to#32004
Chris Rebert於 2012年10月24日星期三UTC+8下午2時07分29秒寫道:
> On Tue, Oct 23, 2012 at 10:23 PM, seektime <michael.j.krause@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:
> 
> 
> 
> 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. 

> 
> >   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']
> 
> <snip>
> 
> >>>> seq
> 
> > '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.

[toc] | [prev] | [next] | [standalone]


#32087

Fromseektime <michael.j.krause@gmail.com>
Date2012-10-24 21:27 -0700
Message-ID<d66a4294-0fc5-4435-8940-6f250467341f@googlegroups.com>
In reply to#32004
On Tuesday, October 23, 2012 11:07:29 PM UTC-7, Chris Rebert wrote:
> On Tue, Oct 23, 2012 at 10:23 PM, seektime <michael.j.krause@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:
> 
> 
> 
> 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']
> 
> <snip>
> 
> >>>> seq
> 
> > '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).

[toc] | [prev] | [next] | [standalone]


#32090

FromChris Rebert <clp2@rebertia.com>
Date2012-10-24 21:52 -0700
Message-ID<mailman.2812.1351140730.27098.python-list@python.org>
In reply to#32087
On Wed, Oct 24, 2012 at 9:27 PM, seektime <michael.j.krause@gmail.com> wrote:
> On Tuesday, October 23, 2012 11:07:29 PM UTC-7, Chris Rebert wrote:
<snip>
>> 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).

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

[toc] | [prev] | [next] | [standalone]


#32088

Fromseektime <michael.j.krause@gmail.com>
Date2012-10-24 21:27 -0700
Message-ID<mailman.2810.1351139258.27098.python-list@python.org>
In reply to#32004
On Tuesday, October 23, 2012 11:07:29 PM UTC-7, Chris Rebert wrote:
> On Tue, Oct 23, 2012 at 10:23 PM, seektime <michael.j.krause@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:
> 
> 
> 
> 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']
> 
> <snip>
> 
> >>>> seq
> 
> > '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).

[toc] | [prev] | [next] | [standalone]


#32016

FromPeter Otten <__peter__@web.de>
Date2012-10-24 09:47 +0200
Message-ID<mailman.2739.1351064865.27098.python-list@python.org>
In reply to#31991
Chris Rebert wrote:

> line.strip().split()

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

>>> line = " a b c \n"
>>> line.split() == line.strip().split()
True

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

[toc] | [prev] | [next] | [standalone]


#32022

FromPeter Otten <__peter__@web.de>
Date2012-10-24 11:04 +0200
Message-ID<mailman.2743.1351069472.27098.python-list@python.org>
In reply to#31991
Peter Otten wrote:

Brave new words:

> immortable

should be "immortal"

[toc] | [prev] | [next] | [standalone]


#32053

FromTerry Reedy <tjreedy@udel.edu>
Date2012-10-24 11:56 -0400
Message-ID<mailman.2782.1351094205.27098.python-list@python.org>
In reply to#31991
On 10/24/2012 1:23 AM, seektime 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.

If you are going to replace single characters (letters) with single 
characters (digits), use maketrans and translate.

 >>> 'a b c'.translate(str.maketrans('abc', '123'))
'1 2 3'

-- 
Terry Jan Reedy

[toc] | [prev] | [next] | [standalone]


#32057

FromMRAB <python@mrabarnett.plus.com>
Date2012-10-24 18:05 +0100
Message-ID<mailman.2788.1351098350.27098.python-list@python.org>
In reply to#31991
On 2012-10-24 07:07, Chris Rebert wrote:
> On Tue, Oct 23, 2012 at 10:23 PM, seektime <michael.j.krause@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:
>
> 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']
> <snip>
>>>>> seq
>> '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]

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

[toc] | [prev] | [next] | [standalone]


#32058

Fromwxjmfauth@gmail.com
Date2012-10-24 10:27 -0700
Message-ID<f48417af-de29-4be5-b80a-fef738888e7f@googlegroups.com>
In reply to#31991
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
> 
> ... 
> 
> 
> 
> >>> 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

[toc] | [prev] | [next] | [standalone]


#32059

FromDemian Brecht <demianbrecht@gmail.com>
Date2012-10-24 10:36 -0700
Message-ID<mailman.2789.1351100215.27098.python-list@python.org>
In reply to#32058
On 2012-10-24, at 10:27 AM, wxjmfauth@gmail.com wrote:
> Not so sure what you mean by an "array of integers".


I wasn't entirely sure about that either. I assumed given the subject that it was just a 1-D array and could then be accessed by arr[(y * width) + x].

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



[toc] | [prev] | [next] | [standalone]


#32064

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2012-10-24 15:57 -0400
Message-ID<mailman.2793.1351108690.27098.python-list@python.org>
In reply to#31991
On Wed, 24 Oct 2012 11:04:38 +0200, Peter Otten <__peter__@web.de>
declaimed the following in gmane.comp.python.general:

> Peter Otten wrote:
> 
> Brave new words:
> 
> > immortable
> 
> should be "immortal"

	Readlines() isn't immortal... It's a lich
http://en.wikipedia.org/wiki/Lich
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
        wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [next] | [standalone]


#32091 — [OT] Re: turn list of letters into an array of integers

FromPeter Otten <__peter__@web.de>
Date2012-10-25 07:47 +0200
Subject[OT] Re: turn list of letters into an array of integers
Message-ID<mailman.2813.1351144053.27098.python-list@python.org>
In reply to#31991
Dennis Lee Bieber wrote:

> On Wed, 24 Oct 2012 11:04:38 +0200, Peter Otten <__peter__@web.de>
> declaimed the following in gmane.comp.python.general:
> 
>> Peter Otten wrote:
>> 
>> Brave new words:
>> 
>> > immortable
>> 
>> should be "immortal"
> 
> 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!

[toc] | [prev] | [next] | [standalone]


Page 1 of 2  [1] 2  Next page →

Back to top | Article view | comp.lang.python


csiph-web