473,890 Members | 1,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting a multidimensiona l array by multiple keys

Hello everyone,

can I sort a multidimensiona l array in Python by multiple sort keys? A
litte code sample would be nice!

Thx,
Rehceb

Mar 31 '07
16 3642
Peter Otten <__*******@web. dewrote:
Duncan Booth wrote:
>>>>from operator import itemgetter
data.sort(k ey=itemgetter(0 ))
data.sort(k ey=itemgetter(1 ))
data.sort(k ey=itemgetter(4 ))
data.sort(k ey=itemgetter(3 ))

Or, in Python 2.5:
>>>data.sort(ke y=itemgetter(3, 4, 1, 0))
Thanks, I'd forgotten itemgetter had that strangley assymmetric behaviour
of returning either a single value or a tuple.
Mar 31 '07 #11
Rehceb Rotkiv escreveu:
Hello everyone,

can I sort a multidimensiona l array in Python by multiple sort keys? A
litte code sample would be nice!
class MyList(list):
# This is the index of the element to be compared
CmpIndex=0

# Comparision methods
@staticmethod
def __cmp_pars(x,y) :
if isinstance(x,My List):
x=x[MyList.CmpIndex]
if isinstance(y,My List):
y=y[MyList.CmpIndex]
return x,y
def __cmp__(self,ot her):
s,o=MyList.__cm p_pars(self,oth er)
return cmp(s,o)
def __lt__(self,oth er):
s,o=MyList.__cm p_pars(self,oth er)
return s<o
def __le__(self,oth er):
s,o=MyList.__cm p_pars(self,oth er)
return s<=o
def __gt__(self,oth er):
s,o=MyList.__cm p_pars(self,oth er)
return s>o
def __ge__(self,oth er):
s,o=MyList.__cm p_pars(self,oth er)
return s>=o
def __eq__(self,oth er):
s,o=MyList.__cm p_pars(self,oth er)
return s==o
def __ne__(self,oth er):
s,o=MyList.__cm p_pars(self,oth er)
return s!=o

Use:

x=MyList(<list of lists>)
MyList.CmpIndex =2 # Compare by index 2
x.sort()

May be there is a better solution ...
HTH
Paulo
Apr 2 '07 #12
Thomas Krüger <ne********@nos pam.nowire.orgw rote:
Rehceb Rotkiv schrieb:
can I sort a multidimensiona l array in Python by multiple sort keys? A
litte code sample would be nice!

You can pass a function as argument to the sort method of a list.
The function should take two arguments and return -1, 0 or 1 as
comparison result. Just like the cmp function.

This will objects in list obj_lst by their id attributes:

def sorter(a, b):
return cmp(a.id, b.id)

obj_lst.sort(so rter)
A MUCH better way to obtain exactly the same semantics would be:

def getid(a):
return a.id

obj_list.sort(k ey=getid)
Alex
Apr 2 '07 #13
Alex Martelli schrieb:
Thomas Krüger <ne********@nos pam.nowire.orgw rote:
>def sorter(a, b):
return cmp(a.id, b.id)

obj_lst.sort(s orter)

A MUCH better way to obtain exactly the same semantics would be:

def getid(a):
return a.id

obj_list.sort(k ey=getid)
Frankly speaking the purpose of the example was to show how to pass a
function as argument for the sort method.
Your code may be more efficient but it explains something different.

Thomas
Apr 2 '07 #14
Thomas Krüger wrote:
Alex Martelli schrieb:
>Thomas Krüger <ne********@nos pam.nowire.orgw rote:
>>def sorter(a, b):
return cmp(a.id, b.id)

obj_lst.sort( sorter)
A MUCH better way to obtain exactly the same semantics would be:

def getid(a):
return a.id

obj_list.sort( key=getid)

Frankly speaking the purpose of the example was to show how to pass a
function as argument for the sort method.
Your code may be more efficient but it explains something different.
Yes, but there's almost never a reason to use the cmp= argument to
sort() anymore. It's almost always better to use the key= argument.

STeVe
Apr 2 '07 #15
Steven Bethard:
there's almost never a reason to use the cmp= argument to
sort() anymore. It's almost always better to use the key= argument.
I always use key now, but maybe cmp uses less memory. There can be few
situations where cmp is better still.

Bye,
bearophile

Apr 2 '07 #16
Steven Bethard <st************ @gmail.comwrote :
Thomas Krüger wrote:
Alex Martelli schrieb:
Thomas Krüger <ne********@nos pam.nowire.orgw rote:
def sorter(a, b):
return cmp(a.id, b.id)

obj_lst.sort(s orter)
A MUCH better way to obtain exactly the same semantics would be:

def getid(a):
return a.id

obj_list.sort(k ey=getid)
Frankly speaking the purpose of the example was to show how to pass a
function as argument for the sort method.
Your code may be more efficient but it explains something different.

Yes, but there's almost never a reason to use the cmp= argument to
sort() anymore. It's almost always better to use the key= argument.
Exactly. Passing a "comparison function" rather than a key-extraction
function is rarely a good idea -- except for some extremely complicated
cases involving e.g. certain string (or more complicated) fields needing
to be sorted in the reverse direction from others. In practice, the
existence of that argument and its prominent position as the first
positional argument is due entirely to backwards compatibility issues.
Alex
Apr 2 '07 #17

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

Similar topics

1
13669
by: Brian | last post by:
I have an array like this: $events = array( array( '2003-07-01', 'Event Title 1', '1' //ID Number (not unique) ), array( '2003-07-02',
5
10927
by: Rob Tweed | last post by:
Probably a simple question but I can't find the answer anyway. Specifically, is it possible to copy a multidimensional array into the $_SESSION array - ie a deep clone of all keys and data? I naively assumed that $_SESSION = $myArray ; would work but it doesn't appear to work. Is there a single function
3
2990
by: Paul Kirby | last post by:
Hello All I am trying to update me code to use arrays to store a group of information and I have come up with a problem sorting the multiple array :( Array trying to sort: (7 arrays put into an array) and I want to sort on Descending. This is displayed using print_r() function. Array
0
3250
by: Brian Henry | last post by:
Here is another virtual mode example for the .NET 2.0 framework while working with the list view. Since you can not access the items collection of the list view you need to do sorting another way... here is my code on how I did it to help anyone starting out get an idea of how to use virtual mode in ..NET 2.0 Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared
11
7817
by: garyhoran | last post by:
Hi Guys, I have a collection that contains various attributes (stuff like strings, DateTime and Timespan) . I would like to access the collection in various orders at different points in the application ie sometimes I want to cycle through the values in the collection in DateTime order while at other times in TimeSpan order. Ideally I would like multiple keys - such as Timespan within DateTime order but maybe that is asking too much.
1
9803
by: Chuy08 | last post by:
If I have a multidimensional array like the following: Array $records =Array 0 = 30 year, 6.0; 1 = 30 year, 6.0; 2 = Pay Option, 1.0; 3 = Pay Option, 1.0; How could I flatten this to achieve an array that only has unique Product
5
2325
by: LittleCake | last post by:
Hi All, I have a multidimensional array where each sub-array contains just two entries, which indicates a relationship between those two entries. for example the first sub-array: =Array ( =30 =31 )
3
7360
KevinADC
by: KevinADC | last post by:
If you are entirely unfamiliar with using Perl to sort data, read the "Sorting Data with Perl - Part One and Two" articles before reading this article. Beginning Perl coders may find this article uses unfamiliar terms and syntax. Intermediate and advanced Perl coders should find this article useful. The object of the article is to inform the reader, it is not about how to code Perl or how to write good Perl code, but to teach the Schwartzian...
9
4507
by: Slain | last post by:
I need to convert a an array to a multidimensional one. Since I need to wrok with existing code, I need to modify a declaration which looks like this In the .h file int *x; in a initialize function: x = new int;
0
10802
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
10910
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
10452
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9618
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 project—planning, coding, testing, and deployment—without 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...
1
8009
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7161
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
5837
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...
1
4667
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
2
4260
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.