473,663 Members | 2,694 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem with custom sort function .... long

Hello all,
I am relatively new to python but I am having an issue with custom
sort functions..

I am trying to sort a list of lists or tuples with arbitrary ascending
or descending sorts. For example given a list of tuples
('firstname','l astname','age') I want to be able to sort lastname
descending, firstname ascending and age ascending...

I wrote a custom function generator to generate a sort function based
on an input list of column numbers and sort direction. Sort seems to
sort the first column ascending regardless of what the sort function
says. I also googled this group for other solutions and found a more
elegant one than mine but with the same results.

Here is my code and result:
sortList = [('2','D'),('1', 'D'),('0','D')]
dataList = []
dataList.append (['a','a','b'])
dataList.append (['a','a','a'])
dataList.append (['a','a','c'])
dataList.append (['a','b','a'])
dataList.append (['a','b','b'])
dataList.append (['a','b','c'])
dataList.append (['a','c','a'])
dataList.append (['a','c','b'])
outStr = 'def custSort( a, b):\n'
depth = 1

for sortPair in sortList:
indent = " "
curDent = depth * indent
outStr += curDent + 'if a[' + sortPair[0] + '] == b[' +
sortPair[0] + ']:\n'
depth += 1

depth -= 1
outStr += curDent + indent + 'return 0\n'
for j in range( len(sortList)-1, -1, -1 ):
curDent = depth * indent
print sortList[j][1]
if sortList[j][1] == 'A':
compareSym = '>'
elif sortList[j][1] == 'D':
compareSym = '<'
else:
print 'SORT DIRECTION ERROR ' + sortList[j][1]
outStr += curDent + 'elif a[' + sortList[j][0] + '] ' + compareSym
+ ' b[' + sortList[j][0] + ']:\n'
outStr += curDent + indent + 'return 1\n'
outStr += curDent + 'else:\n'
outStr += curDent + indent + 'return -1\n'
depth -= 1

print outStr
exec( outStr )
dataList.sort( custSort )
print str( dataList )
*************** ************
results:
D
D
D
def custSort( a, b):
if a[2] == b[2]:
if a[1] == b[1]:
if a[0] == b[0]:
return 0
elif a[0] < b[0]:
return 1
else:
return -1
elif a[1] < b[1]:
return 1
else:
return -1
elif a[2] < b[2]:
return 1
else:
return -1

[['a', 'b', 'c'], ['a', 'a', 'c'], ['a', 'c', 'b'], ['a', 'b', 'b'],
['a', 'a', 'b'], ['a', 'c', 'a'], ['a', 'b', 'a'], ['a', 'a', 'a']]

and Manuel Garcia's solution and results:
sortList = [(0,-1),(1,-1),(2,-1)]
dataList = []
dataList.append (['a','a','b'])
dataList.append (['a','a','a'])
dataList.append (['a','a','c'])
dataList.append (['a','b','a'])
dataList.append (['a','b','b'])
dataList.append (['a','b','c'])
dataList.append (['a','c','a'])
dataList.append (['a','c','b'])

def make_sort_f(lis t0):
def f(a,b):
for (i,m) in list0:
if a[i] == b[i]: continue
return m * cmp(a[i],b[i])
return 0
return f

dataList.sort( make_sort_f( sortList ) )
print str(dataList)

Results:
[['a', 'c', 'b'], ['a', 'c', 'a'], ['a', 'b', 'c'], ['a', 'b', 'b'],
['a', 'b', 'a'], ['a', 'a', 'c'], ['a', 'a', 'b'], ['a', 'a', 'a']]

is this an issue with sort or is my code screwy? Thanks in advance
for any help!

Ken R.
Jul 18 '05 #1
2 3416

"Ken R." <kr*****@hotmai l.com> wrote in message
news:1e******** *************** **@posting.goog le.com...
Hello all,
I am relatively new to python but I am having an issue with custom
sort functions..
Athough they seem to be working fine!
I am trying to sort a list of lists or tuples with arbitrary ascending or descending sorts. For example given a list of tuples
('firstname','l astname','age') I want to be able to sort lastname
descending, firstname ascending and age ascending...

I wrote a custom function generator to generate a sort function based on an input list of column numbers and sort direction. Sort seems to
sort the first column ascending regardless of what the sort function
says. I also googled this group for other solutions and found a more elegant one than mine but with the same results.
Given that your example data all have 'a' in the first column, these
statements of ill behavior make no sense!
Here is my code and result:
sortList = [('2','D'),('1', 'D'),('0','D')]
dataList = []
dataList.append (['a','a','b'])
dataList.append (['a','a','a'])
dataList.append (['a','a','c'])
dataList.append (['a','b','a'])
dataList.append (['a','b','b'])
dataList.append (['a','b','c'])
dataList.append (['a','c','a'])
dataList.append (['a','c','b'])
You could just as well write dataList as a single literal.

[snip]
[['a', 'b', 'c'], ['a', 'a', 'c'], ['a', 'c', 'b'], ['a', 'b', 'b'],
['a', 'a', 'b'], ['a', 'c', 'a'], ['a', 'b', 'a'], ['a', 'a', 'a']]
and columns 2, 1, and 0 are descending (non-increasing) in that order,
just as you asked. What different were you expecting given the input.
and Manuel Garcia's solution and results:
sortList = [(0,-1),(1,-1),(2,-1)] .... Results:
[['a', 'c', 'b'], ['a', 'c', 'a'], ['a', 'b', 'c'], ['a', 'b', 'b'],
['a', 'b', 'a'], ['a', 'a', 'c'], ['a', 'a', 'b'], ['a', 'a', 'a']]
Again, just as requested. Same question.
is this an issue with sort or is my code screwy?


Perhaps your understanding of ascending and descending? or of nested
sorting?

Terry J. Reedy
Jul 18 '05 #2
> Given that your example data all have 'a' in the first column, these
statements of ill behavior make no sense!

Oh my! One would think that I just dashed off a question to the group
without spending any time on the problem (not the case). No excuses
for my oversight but thanks for your gentle reply :).
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2073
by: Rachel Forder | last post by:
Hi All, I have a problem related to the sort function provided by STL. class A{ A(string, string, int); string itemA; string itemB; int itemC; };
20
4054
by: Xah Lee | last post by:
Sort a List Xah Lee, 200510 In this page, we show how to sort a list in Python & Perl and also discuss some math of sort. To sort a list in Python, use the “sort” method. For example: li=;
3
3052
by: Ed Sutton | last post by:
I need to do a custom sort on a TreeView. I have various object types associated with the TreeNode Tag property. I want to sort objects of the same type at the top of the list, other objects at the bottom. I found some scraps of code in various postings that I am trying to get to work. I can not seem to get any meaningful data back from the CompareFunc callback. According to MSDN, The lParam1 and lParam2 parameters correspond to the...
5
1563
by: TM | last post by:
I am using an access database in my vb.net application and it is tied to a datagrid. My problem is that the field I want to sort on is a text field, 5 characters long, and it contains not only numbers but some fields are text. When I sort the table in access, or use the "order by" sql statement, it seems to want to put the numbers first, then the alpha after. I realize this is probably the proper behavior, but is there any way I can
0
1055
by: Gene Hubert | last post by:
I'm doing a custom sort in a datagrid. I'm overriding mousedown and doing the sort on a hidden column in addition to the column that the user clicked on. After the custom sort, I still need to show the little arrow on the column header that shows that the column is sorted and whether the sort is ascending or descending. How to I programatically control the little arrow on the column header?
3
1032
by: Neil | last post by:
Anyone know how to do a custom sort of a datagrid when a column header is clicked? Thanks
2
4880
by: Emma Burrows | last post by:
I have created a typed dataset in .Net 2.0 based on an Access database, and set up various methods to retrieve specific data from the tables, etc (great fun). However, I need to implement a custom sort order on a text column. I know how to implement this in an IComparer and apply it to a custom collection or an array, but I don't see an easy way to tie this up with my strongly typed dataset (short of adding the extra step of feeding it into...
5
4699
by: Ethan Strauss | last post by:
Hi, I want to be able to create a custom sort order for a Sorted List. Specifically, I have a grid which goes from A1 to H12. The default sort gives me A10, A11, A1, A2 ... I would like to change it so that it first sorts by the alphabetical character and then the number. I have figured out that I need to use IComparer, but I can't figure how to set up IComparer. Can anyone help? Thanks! Ethan
0
1046
by: =?iso-8859-1?Q?=22Orlando_D=F6hring=22?= | last post by:
Dear community, I want to use the sort function to sort a (nested) list. General information can be found below. http://www.python.org/doc/2.4.2/lib/typesseq-mutable.html http://wiki.python.org/moin/HowTo/Sorting http://www.python.org/doc/2.4.4/whatsnew/node12.html I want to solve the following problem. Given a list I do not only want to retrieve the sorted list but also the position of the original elements (IX below). The example is...
0
8436
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8771
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8548
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7371
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5657
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4182
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4349
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2763
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.