Take the 2-minute tour ×

I was wondering if you guys had any input on how to efficiently go about doing this, I currently have a working implementation using Python's collections class.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

It depends on how much memory you have available (and the size of the files of course).

If you have enough memory available than I'd personally just take the easy way and create a list of all items and do a sort() on them.

Something like this:

# Read all except the first (header) lines
lines = file('1.txt').readlines()[1:]
lines += file('2.txt').readlines()[1:]

lines.sort(key=lambda x: int(x.split()[0]))

print ''.join(lines)

Alternative for the lambda:

def key(x):
    return int(x.split()[0])
share|improve this answer
Chose this because it's the most Pythonic answer, and the one a variation of which I wound up using. Thank you go to the two of you though, great answers. –  Louis93 May 26 '12 at 17:29
@Louis93: the lambda functions are pretty much the same as normal functions but without a name. This is just a function that takes a parameter x and returns int(x.split()[0]). –  Wolph May 26 '12 at 21:33
@Louis93: I've added the normal version of the lambda for clarity :) –  Wolph May 26 '12 at 21:34
>>> from itertools import islice
>>> from operator import itemgetter
>>> files = ('1.txt','2.txt')
>>> lines = (map(int,line.split()) for f in files
             for line in islice(open(f),1,None))
>>> sorted(lines,key=itemgetter(0))
[[1, 23112, 3], [2, 32344, 1], [12, 19872, 0], [123, 12243, 1], [221, 39873, 5], [234, 34555, -4]]
share|improve this answer

Your Answer


