Project

General

Profile

« Previous | Next » 

Revision 189

sort: Can sort on multiple columns

View differences:

scripts/util/sort
4 4
import csv
5 5
import sys
6 6

  
7
def by_idx(list_, idxes): return [list_[i] for i in idxes]
8

  
7 9
def main():
8
    try: _prog_name, col_num = sys.argv
9
    except ValueError:
10
        raise SystemExit('Usage: '+sys.argv[0]+' col_num <map >sorted_map')
11
    col_num = int(col_num) # 0-based
10
    col_nums = sys.argv[1:]
11
    if col_nums == []:
12
        raise SystemExit('Usage: '+sys.argv[0]+' col_num... <map >sorted_map')
13
    col_nums = map(int, col_nums) # 0-based
12 14
    
13 15
    # Sort map
14 16
    reader = csv.reader(sys.stdin)
15 17
    cols = reader.next()
18
    def get_sort_by(row): return by_idx(row, col_nums)
16 19
    rows = list(reader)
17
    rows.sort(lambda row0, row1: cmp(row0[col_num], row1[col_num]))
20
    rows.sort(lambda *rows: cmp(*map(get_sort_by, rows)))
18 21
    writer = csv.writer(sys.stdout)
19 22
    writer.writerow(cols)
20 23
    map(writer.writerow, rows)

Also available in: Unified diff