名簿の並び替え

適当にオプションで切り替えられるように。そしてファイルの入出力は UNIX 流儀で。

import sys, fileinput

class Person(object):
    __slots__ = 'firstname lastname'.split()

    def __init__(self, lastname, firstname):
        self.firstname = firstname
        self.lastname = lastname

    def __cmp__(self, other):
        return cmp((self.lastname, self.firstname),
                   (other.lastname, other.firstname))

    def initial_form(self):
        return '%c. %s' % (self.firstname[0].upper(),
                           self.lastname.capitalize())

def main(args, sort = False):
    fp = fileinput.input(args)
    names = [Person(*line.rstrip().split()) for line in fp]
    if sort:
        names.sort()
    for name in names:
        print name.initial_form()

if __name__ == '__main__':
    import optparse
    parser = optparse.OptionParser()
    parser.add_option('-s', '--sort', dest = 'sort',
                      action = 'store_true',
                      help = 'sort names before output')
    (opts, args) = parser.parse_args()
    main(args, sort = opts.sort)