[Tutor] Parsing Question

Stefan Behnel stefan_ml at behnel.de
Mon May 11 08:04:40 CEST 2009


Emile van Sebille wrote:
> On 5/9/2009 5:30 PM Alan Gauld said...
> 
>> You should probably be able to do the first for loop as a list
>> comprehension,  but I can't think of how to get the split() call
>> embedded into it right now!
>>
> 
> Just for fun -- given datafile contents...
> 
> 1 one 2 two
> 3 three 4 four
> 5 five 6 six
> 7 seven 8 eight
> 9 nine 10 ten
> 11 eleven 12 twelve
> 
> ... here's a single list comprehension answer
> 
> [ v for k,v in sorted(
>   dict ( (int(pair[0]),pair[1])
>     for pairs in [ dataline.split()
>       for dataline in open(r'c:\datafile').readlines() if dataline ]
>         for pair in (pairs[:2], pairs[2:4]) ).items() )]
> 
> 
> ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
> 'ten', 'eleven', 'twelve']

Kids, don't try this at home ...

Stefan



More information about the Tutor mailing list