[Tutor] string to list

Kent Johnson kent37 at tds.net
Wed Feb 10 15:19:06 CET 2010


On Wed, Feb 10, 2010 at 8:32 AM, Owain Clarke <simbobo at cooptel.net> wrote:
> My son was doing a statistics project in which he had to sort some data by
> either one of two sets of numbers, representing armspan and height of a
> group of children - a boring and painstaking job.  I came across this piece
> of code:-
>
> li=[[2,6],[1,3],[5,4]]  # would also work with li=[(2,6),(1,3),(5,4)]
> li.sort(key=lambda x:x[1] )
> print li
>
> It occurred to me that I could adapt this so that he could input his data at
> the command line and then sort by x:x[0] or x:x[1].  And I have not
> discovered a way of inputting a list, only strings or various number types.

I would do this by reading the data from a file, that way the data
entry is simpler, easier to check and correct, easy to reuse, etc..
Create a file that looks like this:
2 6
1 3
5 4

Read it with code like

f = open('data.txt')
data = []
for line in f:
    line_data = [ int(x) for x in line.split() ]
    data.append(line_data)

or if you like map() and one-line list comprehensions:
data = [ map(int, line.split()) for line in open('data.txt') ]

Then you can sort & process data to your hearts content.

You could also just hard-code the data into your program as a literal list.

Kent


More information about the Tutor mailing list