Mercurial > hg > numerics
annotate numerics/sort.py @ 138:488cb433576c
add d3 from http://d3js.org/d3.v3.min.js
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Sat, 21 Mar 2015 14:54:38 -0700 |
parents | 12649a88545c |
children |
rev | line source |
---|---|
134 | 1 #!/usr/bin/env python |
2 # -*- coding: utf-8 -*- | |
3 | |
4 """ | |
5 sort columned data | |
6 """ | |
7 | |
8 # module globals | |
135
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
9 __all__ = ['sort_arg', 'Sorter'] |
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
10 |
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
11 def sort_arg(string): |
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
12 """converter appropriate for command line argument conversion""" |
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
13 |
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
14 forward = True |
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
15 if string.startswith('-'): |
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
16 forward = False |
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
17 string = string[1:] |
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
18 return (int(string), forward) |
12649a88545c
stubbing: hooking this up to command line
Jeff Hammel <k0scist@gmail.com>
parents:
134
diff
changeset
|
19 |
134 | 20 |
21 class Sorter(object): | |
22 """ | |
23 sorter for columned data | |
24 """ | |
25 | |
26 def __init__(self, *indices): | |
27 """ | |
28 indices -- 2-tuple of (index, forward) | |
29 where forward should be True or False | |
30 """ | |
31 self.indices = indices | |
32 | |
33 def __call__(self, rows): | |
34 return sorted(rows, key=self.key) | |
35 | |
36 def key(self, row): | |
37 retval = [] | |
38 for index, forward in self.indices: | |
39 value = row[index] | |
40 if not forward: | |
41 value = -value | |
42 retval.append(value) | |
43 return tuple(retval) |