Welcome, guest | Sign In | My Account | Store | Cart

A class that defines a compare function that can be used to sort lists of objects by any number of fields.

Python, 51 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class FieldCmp:    
    def __init__(self, fields, rev = 0):
        self.fields = fields
        if rev:
            self.rev = -1
        else:
            self.rev = 1
            
    def cmp(self, s1, s2):
        for field in self.fields:
            f1 = s1.__dict__[field]
            f2 = s2.__dict__[field]
            if f1 < f2:
                return -1 * self.rev
            elif f1 > f2:
                return self.rev
                
        return 0
        
        
if __name__ == '__main__':
    class Struct:
        def __init__(self, a, b, c):
            self.a = a
            self.b = b
            self.c = c

        def __repr__(self):
            return repr((self.a, self.b, self.c))
            
    l = [Struct(10, 20, 20), Struct(10, 10, 20), Struct(30, 20, 30)]
    
    ll = l[:]
    fc = FieldCmp(['a'])
    ll.sort(fc.cmp)
    print ll
            
    ll = l[:]
    fc = FieldCmp(['a'], 1)
    ll.sort(fc.cmp)
    print ll

    ll = l[:]
    fc = FieldCmp(['a', 'b'])
    ll.sort(fc.cmp)
    print ll

    ll = l[:]
    fc = FieldCmp(['a', 'b'], 1)
    ll.sort(fc.cmp)
    print ll
Created by Henk Punt on Sat, 27 Apr 2002 (PSF)
Python recipes (4591)
Henk Punt's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks