partial list sort

Manuel M. Garcia mgarcia at cole-switches.com
Wed Oct 9 14:31:06 EDT 2002


On Wed, 9 Oct 2002 11:41:41 +0200, jsaul <jsaul at gmx.de> wrote:

>What I want is
>
>    [[3, 'A'], [2, 'B'], [1, 'C'], [6, 'A'], [5, 'B'], [4, 'C']]

# would not recommend using the name 'list' because 'list' is already
# defined as a built in function
# so use 'list0' instead
list0 = [ [1,'C'], [2,'B'], [3,'A'],
          [4,'C'], [5,'B'], [6,'A'],
          [-13,'B'], [7,'C'], [19,'A'] ]

print 'before: %s' % (list0)

# probably faster to reverse the 2 element lists, sort without passing
# a function, then reverse the 2 element lists back
# remember, sort and reverse work in place, return None
for k in range(len(list0)): list0[k].reverse()

for k in range(0, len(list0), 3):
    a = list0[k:k+3]
    a.sort()
    list0[k:k+3] = a

for k in range(len(list0)): list0[k].reverse()

print 'after: %s' % (list0)

before: [[1, 'C'], [2, 'B'], [3, 'A'], [4, 'C'], [5, 'B'], [6, 'A'],
[-13, 'B'], [7, 'C'], [19, 'A']]
after: [[3, 'A'], [2, 'B'], [1, 'C'], [6, 'A'], [5, 'B'], [4, 'C'],
[19, 'A'], [-13, 'B'], [7, 'C']]



More information about the Python-list mailing list