another way to sort like l.sort(key=lambda x:(x[0][0], -x[1][0]))
sajuptpm
sajuptpm at gmail.com
Wed Sep 8 02:39:13 EDT 2010
Detailed Description
---------------------
l1 = []
l2 = [
((3,8),(1,2)),
((1,3),(1,7)),
((7,0),(1,8)),
((4,2),(1,2)),
((2,9),(9,1))
]
I need to take each item from l2 and insert into l1 with first
element(column)(3,1,7,4,2) sorted in ascending order and second
element(column)(8,3,0,2,9) sorted in descending order.
#SORTING
for k in l2:
flag=True
for i, v in enumerate(l1):
if v <= k:
l1.insert(i,k)
flag = False
break
if flag:
l1.append(k)
for a in l1:
print a
output
-------
((7, 0), (1, 8))
((4, 2), (1, 2))
((3, 8), (1, 2))
((2, 9), (9, 1))
((1, 3), (1, 7))
This will not give l1 with first element(column)(3,1,7,4,2) sorted in
ascending order and second element(column)(8,3,0,2,9) sorted in
descending order.
-------------- I added a -ve signe to all first elements
l2 = [
((-3,8),(1,2)),
((-1,3),(1,7)),
((-7,0),(1,8)),
((-4,2),(1,2)),
((-2,9),(9,1))
]
#SORTING
for k in l2:
flag=True
for i, v in enumerate(l1):
if v <= k:
l1.insert(i,k)
flag = False
break
if flag:
l1.append(k)
for a in l1:
print a
output
-------
((-1, 3), (1, 7))
((-2, 9), (9, 1))
((-3, 8), (1, 2))
((-4, 2), (1, 2))
((-7, 0), (1, 8))
Now output is similar to first elements asc and second elements
desc.But the problem is the -ve sign, i dont need that.
Have any other method to do it??
More information about the Python-list
mailing list