Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
February 27th, 2005, 10:01 PM
 markb_1984
Contributing User

Join Date: Feb 2003
Posts: 154
Time spent in forums: 1 Day 4 h 10 m 39 sec
Reputation Power: 13
Sorting 2d array/list

Simple question I'm sure someone can answer in a jiffy.

I have a 2d array like the following:

array = [['value', 2.454], ['2ndvalue', 6.252], ['3rdvalue', 1.252]...]

I now wish to sort this array by the 2nd numerical attribute. Is there some standard in-built function in python to do this or do I have to write my own code using a standard sorting algorithm???

#2
February 28th, 2005, 01:01 AM
 CyBerHigh
Contributing User

Join Date: Jun 2004
Posts: 461
Time spent in forums: 4 Days 12 h 36 m 28 sec
Reputation Power: 24
there are dictionarys!

theres are basicly like a list, except you can use it to find the a value instead of using the numerical index key.

lucky for you there is a way to build a dictionary from a nested list. the function is dict(). you can find more at pythons web site http://docs.python.org/tut/node7.html#SECTION007500000000000000000
wx_uab disagrees!

#3
February 28th, 2005, 01:23 AM
 wx_uab
Contributing User

Join Date: Jun 2004
Location: Bimingham,AL
Posts: 68
Time spent in forums: 14 h 58 m 22 sec
Reputation Power: 10

Here is another function for making a dictionary from 2 lists

Code:
```def mkDict(self,keyList, valueList, cond=None):
'''
Make a new dict out of two lists. The first list provides keys,
the 2nd provides values. The cond is a function taking 2 arguments:
key and value. Example: lambda k,v:v%2==0
A valid item means its cond(key, value) is true. Only valid items
are included in the returned dict.

>>> a
[0, 1, 2, 3, 4]

>>> b= [chr(x) for x in range(65,70)]
>>> b
['A', 'B', 'C', 'D', 'E']

>>> mkDict(b,a)
{'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3}

>>> mkDict(b,a,lambda x,y:y%2==0)
{'A': 0, 'C': 2, 'E': 4}

Note:
mkDict(a,b) (without the conditional check) is equivalent to
dict(zip(a,b)), which is much faster. If you know there's no
conditional check, better use dict(zip(a,b)) instead.
'''

if cond==None:
return dict(zip(keyList, valueList))
else:
return dict( [(k,v) for k,v in zip(keyList, valueList) if cond(k,v)] )```

Here is another function for sorting a dictionary by value

Code:
```def sort_by_value(self,d):
""" Returns the keys of dictionary d sorted by their values """
items=d.items()
backitems=[ [v[1],v[0]] for v in items]
backitems.sort()
return [ backitems[i][1] for i in range(0,len(backitems))]```

I would convert the array to a dictionary ,sort it and convert it back to 2d array ( list or whatever)

something like this ( havent tested the code below)
Code:
```keys=[]
values=[]
for item in length(array)
keys.append(item[0])
values.append(item[1])
dict = mkDict(keys,values)# defined above
dict = sort_by_value(dict)#defined above

sortedarray= []

for key in dict.keys()
arrayItem=[]
arrayItem.append(key)
arrayItem.append(dict[key])
sortedarray.append(arrayItem)
#your sorted 2d Array is sortedArray here```

Might not be the best way to do this whole thing though

#4
February 28th, 2005, 07:50 AM
 mawe
Contributing User

Join Date: Nov 2004
Posts: 394
Time spent in forums: 1 Day 10 h 6 m 47 sec
Reputation Power: 51
Hi!

I think this is the easiest solution:
Code:
```x = [['a', 2.454],['b', 6.252],['c', 1.252]]
def sort_second(a,b):
return cmp(a[1],b[1])

x.sort(sort_second)
print x```

Regards, mawe
wx_uab disagrees!

#5
February 28th, 2005, 12:41 PM
 wx_uab
Contributing User

Join Date: Jun 2004
Location: Bimingham,AL
Posts: 68
Time spent in forums: 14 h 58 m 22 sec
Reputation Power: 10
I agree totally

Quote:
 Originally Posted by mawe Hi! I think this is the easiest solution: Code: ```x = [['a', 2.454],['b', 6.252],['c', 1.252]] def sort_second(a,b): return cmp(a[1],b[1]) x.sort(sort_second) print x``` Regards, mawe

Above sol is the easiest way to do it, I agree.

#6
February 28th, 2005, 04:35 PM
 wx_uab
Contributing User

Join Date: Jun 2004
Location: Bimingham,AL
Posts: 68
Time spent in forums: 14 h 58 m 22 sec
Reputation Power: 10
Quote:
 Originally Posted by mawe Hi! I think this is the easiest solution: Code: ```x = [['a', 2.454],['b', 6.252],['c', 1.252]] def sort_second(a,b): return cmp(a[1],b[1]) x.sort(sort_second) print x``` Regards, mawe

I agree totally

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Sorting 2d array