partial list sort
jsaul
jsaul at gmx.de
Thu Oct 10 05:41:10 EDT 2002
More information about the Python-list mailing list
Thu Oct 10 05:41:10 EDT 2002
- Previous message (by thread): No tabs in post PLEASE!!! (was Re: partial list sort)
- Next message (by thread): partial list sort
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
* Terry Reedy [2002-10-09 14:50]: > > list=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ] > > print list > > Don't use list as a variable name. It is a builtin type name. I will > call this lis3. > > > 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 > > Tabs are bad for Usenet posting if you want stupid people like me who > use Outlook Express to read posted code. I totally agree, sorry. > > for k in range(0, len(list), 3): > > # sort over ranges: > > sort_components(list[k:k+3]) > > for k in range(0, len(lis3), 3): #not tested > tem = lis3[k:k+3] > sort_components(tem) > lis3[k:k+3] = tem This works, thanks! Though the use of a temporary makes it look somewhat "ugly" doesn't it? ;) I have now changed it so that it returns the list, thus avoiding the temporary: lis3[k:k+3] = sort_components(lis3[k:k+3]) > Since you presumably want to process triples after sorting, I would > suggest going this route. IE > >>> listin=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ] > >>> for item in listin: item.reverse() > ... > >>> listin > [['C', 1], ['B', 2], ['A', 3], ['C', 4], ['B', 5], ['A', 6]] > >>> worklist=[[listin[i],listin[i+1],listin[i+2]] for i in range(0,len(listin),3)] > >>> worklist > [[['C', 1], ['B', 2], ['A', 3]], [['C', 4], ['B', 5], ['A', 6]]] > >>> for triple in worklist: triple.sort() > ... > >>> worklist > [[['A', 3], ['B', 2], ['C', 1]], [['A', 6], ['B', 5], ['C', 4]]] That could be an alternative, though it involves restructuring the list, which can probably be handled somehow. But since copying seems unavoidable anyway, I'd prefer the above approach. That 'item.reverse()' won't work in "real life" because of the actually much more compex data type I want to handle, while the above was just meant as a minimal example to illustrate the problem. Thanks a lot to all who replied! Cheers, jsaul -- Que le gusta rrrodarrr la errre.
- Previous message (by thread): No tabs in post PLEASE!!! (was Re: partial list sort)
- Next message (by thread): partial list sort
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list