Lining Up and PaddingTwo Similar Lists

Paul Rubin http
Fri Aug 29 02:42:29 EDT 2008


"W. eWatson" <notvalid2 at sbcglobal.net> writes:
> [a.dat, c.dat, g.dat, k.dat, p.dat]
> [a.txt, b.txt, g.txt, k.txt r.txt, w.txt]
> 
> What I need is to pair up items with the same prefix and use "None",
> or some marker, to indicate the absence of the opposite item. 

This is functionally influenced but should be straightforward:

    dat = ['a.dat', 'c.dat', 'g.dat', 'k.dat', 'p.dat']
    txt = ['a.txt', 'b.txt', 'g.txt', 'k.txt', 'r.txt', 'w.txt']

    # just get the portion of the filename before the first period
    def prefix(filename):
        return filename[:filename.find('.')]

    # make a dictionary mapping prefixes to filenames
    def make_dict(plist):
        return dict((prefix(a),a) for a in plist)

    pdat = make_dict(dat)
    ptxt = make_dict(txt)

    # get a list of all the prefixes, use "set" to remove
    # duplicates, then sort the result and look up each prefix.
    for p in sorted(set(pdat.keys() + ptxt.keys())):
        print pdat.get(p), ptxt.get(p)



More information about the Python-list mailing list