[Tutor] output sequentially

Peter Otten __peter__ at web.de
Wed Jul 27 08:35:07 CEST 2011


lina wrote:

> I have below file,
> 
> I wish the output following:
> 
> The first field 169 -170 sequential, and then the filed 2 from 1-29,
> ignore the rest 4 fields,
 
>   
>   169CHOL   O28 1612   6.966   6.060   6.429

Read the lines from the file, sort them with a proper key function, write 
the sorted lines to a new file:

with open("source.txt") as instream:
   lines = sorted(instream, key=mykey)

with open("dest.txt", "w") as outstream:
    outstream.writelines(lines)

Now for the mykey() function: what should it look like?
You want to sort by the integer value of the first two columns, so you have 
to split the lines into fields and then remove the non-digits from the 
fields you are interested in. Here's an outline:

def extract_int(field):
   only_digits = ...
   return int(only_digits)

assert extract_int("169CHOL") == 169
assert extract_int("H28") == 28

def mykey(line):
    fields = ...
    # example: ['169CHOL', 'H29', '1611', '6.963', '6.155', '6.395']
    return extract_int(fields[0]), extract_int(fields[1])

assert mykey("169CHOL   H29 1611   6.963   6.155   6.395\n") == (169, 28)

Can you fill in the blanks?




More information about the Tutor mailing list