partial list sort

jsaul jsaul at gmx.de
Wed Oct 9 12:33:45 EDT 2002


* Eddie Corns [2002-10-09 14:48]:
> >    list=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ]
> >    print list
>
> >    def sort_components (list):
> >        def cmp_comp (data1, data2):
> >            if   data1[1] == data2[1]:  return  0
> >            elif data1[1]  < data2[1]:  return -1
> >            return 1
> >        print list
> >        list.sort(cmp_comp)
> >        print list
> >        return
>
> >    for k in range(0, len(list), 3):
> >         # sort over ranges:
> >        sort_components(list[k:k+3])
>
> >    print list
>
> >The resulting output is:
>
> >    [[1, 'C'], [2, 'B'], [3, 'A'], [4, 'C'], [5, 'B'], [6, 'A']]
> >    [[1, 'C'], [2, 'B'], [3, 'A']]
> >    [[3, 'A'], [2, 'B'], [1, 'C']]
> >    [[4, 'C'], [5, 'B'], [6, 'A']]
> >    [[6, 'A'], [5, 'B'], [4, 'C']]
> >    [[1, 'C'], [2, 'B'], [3, 'A'], [4, 'C'], [5, 'B'], [6, 'A']]
>
> >What I want is
>
> >    [[3, 'A'], [2, 'B'], [1, 'C'], [6, 'A'], [5, 'B'], [4, 'C']]
>
> Hint: list[x:y] is a COPY of the elements ie a new list.

That's what I also thought initially. But if in 'sort_components'
I introduce the assignment

    list[0][0] = 9

just before 'list.sort(cmp_comp)', I get the following output:

    [[9, 'C'], [2, 'B'], [3, 'A'], [9, 'C'], [5, 'B'], [6, 'A']]

That it really weird. If the list which is passed to the function
'sort_components' was a copy, then the function shouldn't be able
to modify the original array, right? But the latter *is* being
modified, and the data part of the 'C' components becomes 9.
However, the *order* of the list remains unchanged!

Cheers, jsaul
-- 
Que le gusta rrrodarrr la errre.



More information about the Python-list mailing list