473,407 Members | 2,314 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

Problem with the sort() function

Hi,

I have an array of arrays in the form of
list = [[3,'fork',0.3,1],[2,'fork,0.1,2],[3,'exec',0.2,2]]

The in-built sort(),list.sort() sorts on the first element, if the first
elts are equal then it sorts on the second elt and so on...But i really
dont want to search on the second elt if the first elts are equal...the
1-D lists shud be left in the same position i.e. i want the sorted list to
be [[2,'fork',0.1,2],[3,'fork,0.3,1],[3,'exec',0.2,2]] and not
[[2,'fork',0.1,2],[3,'exec',0.2,2],[3,'fork,0.3,1]].

I tried the following code:

def mysort(x,y):
return x[0]-y[0]

list.sort(mysort)

This somehow seems to work for a small subset of my input...but not for my
real input which has more than 2000 sub-lists(and so obviously i cant trace
each pass..). Can someone tell me what i'm missing?
Jul 18 '05 #1
10 1499
clementine wrote:
Hi,

I have an array of arrays in the form of
list = [[3,'fork',0.3,1],[2,'fork,0.1,2],[3,'exec',0.2,2]]

The in-built sort(),list.sort() sorts on the first element, if the first
elts are equal then it sorts on the second elt and so on...But i really
dont want to search on the second elt if the first elts are equal...the
1-D lists shud be left in the same position i.e. i want the sorted list to
be [[2,'fork',0.1,2],[3,'fork,0.3,1],[3,'exec',0.2,2]] and not
[[2,'fork',0.1,2],[3,'exec',0.2,2],[3,'fork,0.3,1]].


Try this:

Py> from operator import itemgetter
Py> list = [[3,'fork',0.3,1],[2,'fork',0.1,2],[3,'exec',0.2,2]]
Py> list.sort(key=itemgetter(0))
Py> list
[[2, 'fork', 0.10000000000000001, 2], [3, 'fork', 0.29999999999999999, 1], [3, '
exec', 0.20000000000000001, 2]]

If the 'key' argument isn't accepted (i.e. you aren't using Python 2.4), you'll
need to do the decoration manually:

def mysort(iterable, cmp=None, key=None, reverse=False):
"return a sorted copy of its input"
if sys.version_info >= (2,4):
return sorted(iterable, cmp, key, reverse)
seq = list(iterable)
if reverse:
seq.reverse() # preserve stability
if key is not None:
seq = [(key(elem), i, elem) for i, elem in enumerate(seq)]
seq.sort(cmp)
if key is not None:
seq = [elem for (key, i, elem) in seq]
if reverse:
seq.reverse()
return seq

list = mysort([[3,'fork',0.3,1],[2,'fork',0.1,2],[3,'exec',0.2,2]],
key=lambda x: x[0])

(Taken from Raymond's code in:
http://mail.python.org/pipermail/pyt...ry/263275.html)

Cheers,
Nick.

--
Nick Coghlan | nc******@email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #2
Thanx Nick...I forgot to mention im using python 2.2 and along with a host
of other things it doesnt seem to have the enumarate built in function
:(:(:(...is it possible to replace it by something else? I dont think
simulating it will be feasible....

Jul 18 '05 #3
clementine <ka***************@yahoo.com> wrote:
Thanx Nick...I forgot to mention im using python 2.2 and along with a host
of other things it doesnt seem to have the enumarate built in function
:(:(:(...is it possible to replace it by something else? I dont think
simulating it will be feasible....


Here's one I prepared earlier:

if sys.version_info < (2,3):
def enumerate(l):
return zip(range(len(l)), l)

which will suck somewhat on large lists compared to being able to
do it with iterators.

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
Jul 18 '05 #4

Sion Arrowsmith wrote:
clementine <ka***************@yahoo.com> wrote:
Thanx Nick...I forgot to mention im using python 2.2 and along with a hostof other things it doesnt seem to have the enumarate built in function:(:(:(...is it possible to replace it by something else? I dont thinksimulating it will be feasible....
Here's one I prepared earlier:

if sys.version_info < (2,3):
def enumerate(l):
return zip(range(len(l)), l)

which will suck somewhat on large lists compared to being able to
do it with iterators.


Iterators are available in python 2.2
class enumerate:
def __init__(self, inlist):
self.inlist = inlist
self.index = 0

def next(self):
if self.index >= len(self.inlist): raise StopIteration
thisone = self.inlist[self.index]
self.index += 1
return self.index-1, thisone

def __iter__(self):
return self

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml
--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump

bump bump

Jul 18 '05 #5
Nick Coghlan wrote:

def mysort(iterable, cmp=None, key=None, reverse=False):
"return a sorted copy of its input"
if sys.version_info >= (2,4):
return sorted(iterable, cmp, key, reverse)
seq = list(iterable)
if reverse:
seq.reverse() # preserve stability
if key is not None:
seq = [(key(elem), i, elem) for i, elem in enumerate(seq)]
seq.sort(cmp)
if key is not None:
seq = [elem for (key, i, elem) in seq]
if reverse:
seq.reverse()
return seq


You'd be better off defining things once (and using the standard name)
rather than doing a test every time your function is called.
Something like:

import sys
...
if sys.version_info < (2, 3):
def enumerate(iterable): # iterators not yet invented
return zip(range(len(iterable)), iterable)

if sys.version_info < (2, 4):
def sorted(iterable, cmp=None, key=None, reverse=False):
"return a sorted copy of its input"
seq = list(iterable)
if reverse:
seq.reverse() # preserve stability
if key is not None:
seq = [(key(elem), i, elem) for i, elem
in enumerate(seq)]
seq.sort(cmp)
if key is not None:
seq = [elem for (key, i, elem) in seq]
if reverse:
seq.reverse()
return seq

If you like your names better, you can use:

if sys.version_info >= (2, 4):
mysort = sorted
else:
def mysort(iterable, cmp=None, key=None, reverse=False):
...

or even (if you can't be bothered to look up when features happened):

try:
test = enumerate
except NameError:
def enumerate(iterable):
...
try:
test = sorted
except NameError:
def sorted(iterable, cmp=None, key=None, reverse=False):
...
--Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #6
Scott David Daniels wrote:
if sys.version_info < (2, 4):
def sorted(iterable, cmp=None, key=None, reverse=False):
"return a sorted copy of its input"
seq = list(iterable)
if reverse:
seq.reverse() # preserve stability
if key is not None:
seq = [(key(elem), i, elem) for i, elem
in enumerate(seq)]
seq.sort(cmp)
if key is not None:
seq = [elem for (key, i, elem) in seq]
if reverse:
seq.reverse()
return seq


I think you may have some unintended indentation on the 'seq.sort' line
otherwise this only sorts when a key is specified.

Also, you probably want:

if key is not None:
if reverse:
seq = [(key(elem), -i, elem) for i, elem
in enumerate(seq)]
else:
seq = [(key(elem), i, elem) for i, elem
in enumerate(seq)]

to handle the case where both key and reverse are given.
Jul 18 '05 #7
Fuzzyman wrote:
Iterators are available in python 2.2
class enumerate:
def __init__(self, inlist):
self.inlist = inlist
self.index = 0

def next(self):
if self.index >= len(self.inlist): raise StopIteration
thisone = self.inlist[self.index]
self.index += 1
return self.index-1, thisone

def __iter__(self):
return self


A simpler version that works with any iterable (not just sequences):

py> class enumerate(object):
.... def __init__(self, iterable):
.... self._next = iter(iterable).next
.... self._index = -1
.... def __iter__(self):
.... return self
.... def next(self):
.... self._index += 1
.... return self._index, self._next()
....
py> enumerate('abcde')
<__main__.enumerate object at 0x011627F0>
py> list(enumerate('abcde'))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]

STeVe
Jul 18 '05 #8
Scott David Daniels wrote:
or even (if you can't be bothered to look up when features happened):

try:
test = enumerate
except NameError:
def enumerate(iterable):
...
try:
test = sorted
except NameError:
def sorted(iterable, cmp=None, key=None, reverse=False):
...


Ridiculously minor nit, but there's no reason to assign to test:

try:
enumerate
except NameError:
def enumerate(iterable):
...
try:
sorted
except NameError:
def sorted(iterable, cmp=None, key=None, reverse=False):
...

Just evaluating the expression 'enumerate' or 'sorted' should raise the
NameError if they don't exist.

STeVe
Jul 18 '05 #9

clementine wrote:
Thanx Nick...I forgot to mention im using python 2.2 and along with a host of other things it doesnt seem to have the enumarate built in function :(:(:(...is it possible to replace it by something else? I dont think
simulating it will be feasible....


Faced with Nick's one line of code that uses 'enumerate', you have the
choice of building (and testing) an elaborate time machine to make a
SLOW 'enumerate' available for 2.2, or you can just patch Nick's
sorting gadget in a very straightforward manner:

modern as per Nick:
seq = [(key(elem), i, elem) for i, elem in enumerate(seq)]

ancient:
seq = [(key(seq[i]), i, seq[i]) for i in xrange(len(seq))]

Jul 18 '05 #10
Thanks everyone!!:-) Nicks solution coupled with John's modifications
worked great for 2.2!! Yipeee...!!:):)
Jul 18 '05 #11

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

Similar topics

2
by: Ken R. | last post by:
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...
8
by: lok | last post by:
i have a class: template <class T1, class T2> class CPairMapping { public: typedef std::pair<T1, T2> ValuePair_t; typedef std::vector<ValuePair_t> ValueList_t; typedef std::binary_function<...
2
by: Joel | last post by:
I am having some problems compiling my code on Mandrake 10 with g++ (GCC 3.3.2). The problem seems to be in that I try to define a functor that compares two pointer objects, and use that functor to...
20
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: ...
3
by: ritchie | last post by:
Hi all! Still working on this program! Just to recap, I am writing a program to sort an array with four different sort algorythms. I am having a little trouble at the moment though! Now, I...
1
by: tangus via DotNetMonster.com | last post by:
Hello all, I'm really struggling with getting some Active Directory code to work in ASP.NET. Can you please provide assistance? I am executing the following code: Dim enTry As DirectoryEntry =...
4
by: sonu | last post by:
Hi, I have a problem regarding use of a ListviewSorter class which is used to sort the items in the listview. Basically I have a listview with three columns as "Name","Size" and...
7
by: Kamal | last post by:
Hello all, I have a very simple html table with collapsible rows and sorting capabilities. The collapsible row is hidden with css rule (display:none). When one clicks in the left of the...
14
by: Frank | last post by:
Hello everyone, I am having trouble overloading the < operator for an assignment. I use a struct that contains information and I would like to sort this structure using STL sort with my own...
4
pradeepjain
by: pradeepjain | last post by:
i had posted the same code in javascript area !! this i am posting bcos of different problem. as you can see in ma code there is a dropdown called sort ...its sorts the result by the value he...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...
0
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,...
0
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...

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.