[Tutor] string to list

Owain Clarke simbobo at cooptel.net
Wed Feb 10 14:32:52 CET 2010


> Owain Clarke wrote:
>   
>> Please excuse the obviousness of my question (if it is), but I have 
>> searched the documentation for how to generate a list e.g. [(1,2), 
>> (3,4)] from a string "[(1,2), (3,4)]". I wonder if someone could point 
>> me in the right direction.
>>
>> Many thanks
>>
>> Owain Clarke
>>
>>     
Thanks to all who responded between my first and second post.

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

> Stefan

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 realise that I am a bit out of my depth here, but Python just seems like so much fun!!

Owain



More information about the Tutor mailing list