[Tutor] string to list
Stefan Behnel
stefan_ml at behnel.de
Wed Feb 10 15:28:28 CET 2010
Owain Clarke, 10.02.2010 14:32:
>> You may want to add a little bit about your use case. Is that really
>> the input you
>> have to deal with? Where does it come from? Can you control the
>> format? What do
>> you want to do with the list you extract from the string?
>>
>> All of that may have an impact on the right solution.
>
> 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.
Thanks for the explanation, that certainly clears it up.
> 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 rather put them into a file one-per-line, e.g.
2,6
1,3
5,4
and then read that in as input. That way, you can reuse the input multiple
times, even if you discover that your program has a bug or needs a new
feature, or whatever. Having to retype the data will quickly get really
cumbersome.
Something like this should do the job:
children_properties = []
with file("thefile.txt") as f:
for line in f:
if line.count(',') != 1:
# broken line?
print("Ignoring malformed line '%s'" % line)
continue
armspan, height = map(int, line.split(','))
children_properties.append( (armspan, height) )
Then sort and print as you see fit.
> I realise that I am a bit out of my depth here, but Python just seems
> like so much fun!!
The beauty of Python for people who are just starting programming is that
so many things are so surprisingly simply to do that you really quickly get
to think about rather tricky problems, instead of being blocked by syntax.
Keep up the pace! :)
Stefan
More information about the Tutor
mailing list