473,890 Members | 1,686 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 #1
16 3641
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)

Thomas
Mar 31 '07 #2
Rehceb Rotkiv:
can I sort a multidimensiona l array in Python by multiple sort keys? A
litte code sample would be nice!
If you want a good answer you have to give me/us more details, and an
example too.

Bye,
bearophile

Mar 31 '07 #3
If you want a good answer you have to give me/us more details, and an
example too.
OK, here is some example data:

reaction is BUT by the
sodium , BUT it is
sea , BUT it is
this manner BUT the dissolved
pattern , BUT it is
rapid , BUT it is

As each line consists of 5 words, I would break up the data into an array
of five-field-arrays (Would you use lists or tuples or a combination in
Python?). The word "BUT" would be in the middle, with two fields/words
left and two fields/words right of it. I then want to sort this list by

- field 3
- field 4
- field 1
- field 0

in this hierarchy. This is the desired result:

pattern , BUT it is
rapid , BUT it is
sea , BUT it is
sodium , BUT it is
reaction is BUT by the
this manner BUT the dissolved

The first 4 lines all could not be sorted by fields 3 & 4, as they are
identical ("it", "is"), so they have been sorted first by field 1 (which
is also identical: ",") and then by field 0:

pattern
rapid
sea
sodium

I hope I have explained this in an understandable way. It would be cool
if you could show me how this can be done in Python!

Regards,
Rehceb
Mar 31 '07 #4
Wait, I made a mistake. The correct result would be

reaction is BUT by the
pattern , BUT it is
rapid , BUT it is
sea , BUT it is
sodium , BUT it is
this manner BUT the dissolved

because "by the" comes before and "the dissolved" after "it is". Sorry
for the confusion.
Mar 31 '07 #5
Rehceb Rotkiv wrote:
>If you want a good answer you have to give me/us more details, and an
example too.

OK, here is some example data:

reaction is BUT by the
sodium , BUT it is
sea , BUT it is
this manner BUT the dissolved
pattern , BUT it is
rapid , BUT it is

As each line consists of 5 words, I would break up the data into an array
of five-field-arrays (Would you use lists or tuples or a combination in
Python?). The word "BUT" would be in the middle, with two fields/words
left and two fields/words right of it. I then want to sort this list by

- field 3
- field 4
- field 1
- field 0
You're probably looking for the key= argument to list.sort(). If your
function simply returns the fields in the order above, I believe you get
the right thing::
>>s = '''\
.... reaction is BUT by the
.... sodium , BUT it is
.... sea , BUT it is
.... this manner BUT the dissolved
.... pattern , BUT it is
.... rapid , BUT it is
.... '''
>>word_lists = [line.split() for line in s.splitlines()]
def key(word_list):
.... return word_list[3], word_list[4], word_list[1], word_list[0]
....
>>word_lists.so rt(key=key)
word_lists
[['reaction', 'is', 'BUT', 'by', 'the'],
['pattern', ',', 'BUT', 'it', 'is'],
['rapid', ',', 'BUT', 'it', 'is'],
['sea', ',', 'BUT', 'it', 'is'],
['sodium', ',', 'BUT', 'it', 'is'],
['this', 'manner', 'BUT', 'the', 'dissolved']]

STeVe
Mar 31 '07 #6
Rehceb Rotkiv <re****@no.spam .plzwrote:
Wait, I made a mistake. The correct result would be

reaction is BUT by the
pattern , BUT it is
rapid , BUT it is
sea , BUT it is
sodium , BUT it is
this manner BUT the dissolved

because "by the" comes before and "the dissolved" after "it is". Sorry
for the confusion.
>>data = [
"reaction is BUT by the",
"sodium , BUT it is",
"sea , BUT it is",
"this manner BUT the dissolved",
"pattern , BUT it is",
"rapid , BUT it is",
]
>>data = [ s.split() for s in data]
from pprint import pprint
pprint(data )
[['reaction', 'is', 'BUT', 'by', 'the'],
['sodium', ',', 'BUT', 'it', 'is'],
['sea', ',', 'BUT', 'it', 'is'],
['this', 'manner', 'BUT', 'the', 'dissolved'],
['pattern', ',', 'BUT', 'it', 'is'],
['rapid', ',', 'BUT', 'it', 'is']]
>>from operator import itemgetter
data.sort(key =itemgetter(0))
data.sort(key =itemgetter(1))
data.sort(key =itemgetter(4))
data.sort(key =itemgetter(3))
pprint(data )
[['reaction', 'is', 'BUT', 'by', 'the'],
['pattern', ',', 'BUT', 'it', 'is'],
['rapid', ',', 'BUT', 'it', 'is'],
['sea', ',', 'BUT', 'it', 'is'],
['sodium', ',', 'BUT', 'it', 'is'],
['this', 'manner', 'BUT', 'the', 'dissolved']]
Mar 31 '07 #7
On Mar 31, 6:42 am, Rehceb Rotkiv <reh...@no.spam .plzwrote:

(snipped)
As each line consists of 5 words, I would break up the data into an array
of five-field-arrays (Would you use lists or tuples or a combination in
Python?). The word "BUT" would be in the middle, with two fields/words
left and two fields/words right of it. I then want to sort this list by

- field 3
- field 4
- field 1
- field 0


import StringIO

buf = """
reaction is BUT by the
sodium , BUT it is
sea , BUT it is
this manner BUT the dissolved
pattern , BUT it is
rapid , BUT it is
""".lstrip( )

mockfile = StringIO.String IO(buf)

tokens = [ line.split() + [ line ] for line in mockfile ]
tokens.sort(key =lambda l: (l[3], l[4], l[1], l[0]))
for l in tokens:
print l[-1],
--
Hope this helps,
Steven

Mar 31 '07 #8
Duncan Booth wrote:
>>>from operator import itemgetter
data.sort(ke y=itemgetter(0) )
data.sort(ke y=itemgetter(1) )
data.sort(ke y=itemgetter(4) )
data.sort(ke y=itemgetter(3) )
Or, in Python 2.5:
>>data.sort(key =itemgetter(3, 4, 1, 0))
Peter
Mar 31 '07 #9
Thank you all for your helpful solutions!

Regards,
Rehceb
Mar 31 '07 #10

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
9976
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11215
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
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
10908
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
10451
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...
0
7160
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();...
2
4259
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3267
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.