[Tutor] Fwd: how to sort the file out
hugo.yoshi at gmail.com
Wed Sep 7 08:25:07 CEST 2011
forgot to forward this to list, sorry.
---------- Forwarded message ----------
From: Hugo Arts <hugo.yoshi at gmail.com>
Date: Wed, Sep 7, 2011 at 8:24 AM
Subject: Re: [Tutor] how to sort the file out
To: lina <lina.lastname at gmail.com>
On Wed, Sep 7, 2011 at 8:16 AM, lina <lina.lastname at gmail.com> wrote:
> On Wed, Sep 7, 2011 at 1:28 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:
>> I was assuming that the numbers were field 1, and the letter/number
>> combinations were field 2. If I understand him correctly, he wants the
>> lines in file 2 to be arranged such that the order of field two is the
>> same as it is in file 1. In that case, you can do it with one sexy
>> sort() call (and a little preprocessing to load the files), but I
>> don't want to get all into explain and then realize he wants something
>> totally different.
> You understand right.
Well, it is fairly simple. You grab field2 from file1, and put all the
items into a list (should be easy right? open(), readlines(), split(),
grab second item). Then, you grab file2 as a list of tuples (same
procedure as the first file, but you just put the results of split()
right into the list. Then you sort with a key like so:
list2.sort(key=lambda x: list1.index(x))
You see? For each item in the second list, we grab field 2, and look
up what index it has in list1. Then we use that index as the sort key.
That way they'll be sorted like file1 is.
After that it's just a matter of writing back to the file, easy peasy.
More information about the Tutor