473,327 Members | 2,081 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,327 software developers and data experts.

Combined natural and unnatural list sorting

Hello All,

I need to sort a list using an unnatural sequence.

I have a list like so:

foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"]

print foo.sort()

['White/L', 'White/M', 'White/S', 'White/XL', 'Black/M', 'Black/S']
The order that I actually need is:

["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"]
So, in other words, I need the colors sorted alphabetically and the the sizes
sorted logically.

I looked for a while at using comparison functions with sort but I don't think
that will work. Anyone been down this road? Suggestions?

Thanks a million,
Derek

__________________________________
Do you Yahoo!?
Yahoo! Mail - You care about security. So do we.
http://promotions.yahoo.com/new_mail

Jul 18 '05 #1
3 1725
* Derek Basch (2004-06-15 23:38 +0100)
Hello All,

I need to sort a list using an unnatural sequence.

I have a list like so:

foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"]

print foo.sort()

['White/L', 'White/M', 'White/S', 'White/XL', 'Black/M', 'Black/S']

The order that I actually need is:

["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"]

So, in other words, I need the colors sorted alphabetically and the the sizes
sorted logically.

I looked for a while at using comparison functions with sort but I don't think
that will work. Anyone been down this road? Suggestions?


You need some kind of general "function sort" (either using the
"Decorate, Sort, Undecorate" or the "pass a function" idiom):

def funcsort(seq, function, modus = 'dsu'):
"""
sort seq by function(item)
"""

if modus == 'dsu':
seq = [(function(item), index, item) for index, item in enumerate(seq)]
seq.sort()
return [item[2] for item in seq]
elif modus == 'pass':
seq = seq[:]
seq.sort(lambda x, y: cmp(function(x), function(y)))
return seq

This is a common kind of sort problem so you will need this "function
sort" anyway in near future.

Then your problem simply translates to find a function that generates
your sort items like you want them sorted (in this case something like
'White/M' -> ('White', 2) ):

SIZE_MAP = {'S': 1,
'M': 2,
'L': 3,
'XL': 4}

def func(item):
splititem = item.split('/')
return splititem[0], SIZE_MAP[splititem[1]]

print funcsort(foo, func)
Thorsten
Jul 18 '05 #2
Derek Basch wrote:
I have a list like so:

foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"] The order that I actually need is:

["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"] I looked for a while at using comparison functions with sort but I don't
think that will work. Anyone been down this road? Suggestions?


Here's a slightly more complicated approach. Turn what was the "unnatural"
into the "natural" order:

from itertools import count

class Size(object):
all = {}
_nextIndex = count().next

def __new__(cls, name):
try:
return cls.all[name]
except KeyError:
self = object.__new__(cls, name)
self.name = name
self.index = cls._nextIndex()
cls.all[name] = self
return self

def __init__(self, name):
pass

def __lt__(self, other):
return self.index < other.index

def __str__(self):
return self.name

for size in "XXS XS S M L XL XXL".split():
Size(size)
del size

class TShirt(object):
def __init__(self, colorSize):
self.color, size = colorSize.split("/")
self.size = Size(size)

def __lt__(self, other):
if self.color == other.color:
return self.size < other.size
return self.color < other.color

def __str__(self):
return "%s/%s" % (self.color, self.size)

stock = map(TShirt, ["White/M", "White/L", "White/XL", "White/S", "Black/S",
"Black/M"])

# color, size
stock.sort()
for tshirt in stock:
print tshirt
print "---"

# size, color
stock.sort(lambda s, t: cmp(s.size, t.size) or cmp(s.color, t.color))
for tshirt in stock:
print tshirt

Peter

Jul 18 '05 #3
In article <ca*************@news.t-online.com>, __*******@web.de says...
Derek Basch wrote:
I have a list like so:

foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S", "Black/M"]

The order that I actually need is:

["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"]

I looked for a while at using comparison functions with sort but I don't
think that will work. Anyone been down this road? Suggestions?


Here's a slightly more complicated approach. Turn what was the "unnatural"
into the "natural" order:

from itertools import count

class Size(object):
all = {}
_nextIndex = count().next


Wow! Thanks for sharing the knowledge everyone. I think I am starting to
get my head around these sorting idioms. It will take me a bit to study
all the code you sent. Every day the forums remind me what a noob I am
;)
Jul 18 '05 #4

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

Similar topics

0
by: C. Barnes | last post by:
Summary: Sorts strings in a way that seems natural to humans. If the strings contain integers, then the integers are ordered numerically. For example, sorts into the order . Code:
1
by: Connelly Barnes | last post by:
Summary: Sorts strings in a way that seems natural to humans. If the strings contain integers, then the integers are ordered numerically. For example, sorts into the order . Code: ...
10
by: Kent | last post by:
Hi! I want to store data (of enemys in a game) as a linked list, each node will look something like the following: struct node { double x,y; // x and y position coordinates struct enemy...
3
by: chellappa | last post by:
hi this simple sorting , but it not running...please correect error for sorting using pointer or linked list sorting , i did value sorting in linkedlist please correct error #include<stdio.h>...
0
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...
44
by: Josh Mcfarlane | last post by:
Just out of curiosity: When would using std::list be more efficient / effective than using other containers such as vector, deque, etc? As far as I'm aware, list doesn't appear to be...
9
by: Fish Womper | last post by:
I am at best a part time developer of Access databases. I use Access 2.0, as this is all my employer has on its computers. Even so, to use this ancient version requires a fairly convoluted...
16
by: Michael M. | last post by:
How to find the longst element list of lists? I think, there should be an easier way then this: s1 = s2 = s3 = if len(s1) >= len(s2) and len(s1) >= len(s3): sx1=s1 ## s1 ist längster
5
by: jrod11 | last post by:
hi, I found a jquery html table sorting code i have implemented. I am trying to figure out how to edit how many colums there are, but every time i remove code that I think controls how many colums...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.