how two join and arrange two files together
Peter Otten
__peter__ at web.de
Sat Jul 18 06:40:01 EDT 2009
amrita at iisermohali.ac.in wrote:
>> Can you make an effort to express clearly what you want, preferrably with
>> a simple and unambiguous example?
> I want to join column of two different data file but i want that the
> entries will match (example i mentioned in my first mail, the position of
> ALA eill match) if its not matching then it will get printed as such.
Just say "No" if you mean it.
My best guess:
from collections import defaultdict
def merge(sources):
blanks = [blank for items, blank, keyfunc in sources]
d = defaultdict(lambda: blanks[:])
for index, (items, blank, keyfunc) in enumerate(sources):
for item in items:
d[keyfunc(item)][index] = item
for key in sorted(d):
yield d[key]
if __name__ == "__main__":
from StringIO import StringIO
a = StringIO("""\
a alpha
c beta
d gamma
""")
b = StringIO("""\
a one
b two
d three
e four
""")
c = StringIO("""\
a 111
b 222
f 333
""")
def key(line):
return line[:1]
def source(stream, blank="", key=key):
return (line.strip() for line in stream), blank, key
for m in merge([source(x) for x in [a,b,c]]):
print "|".join(c.ljust(10) for c in m)
More information about the Python-list
mailing list