Reputation: 251
I am trying to sort a list by multiple conditions using this code.
lis = sorted([lsDataSorted[i:i+8] for i in range(0,len(lsDataSorted),8)],key=lambda x:(x[7],int(x[5])-int(x[6]),x[5],x[0]),reverse=True)
Now, we don't need to bother talking about what each object is, but we see that I have an "reverse" sorting function. Now, my last condition x[0]
happens to be a list of names. By using the reverse=True
, we know that the sorting will be in reverse order (z-a). My question is, can I "reverse" back to normal only for the last condition? If yes, then how?
Upvotes: 1
Views: 140
Reputation: 882731
I would recommend wrapping each chunk of lsDataSorted
into a custom class that will enforce comparison by your complex condition. For example:
import functools
@functools.total_ordering
class Compare(object):
def __init__(self, chunk):
self.x = chunk[7], int(chunk[5]) - int(chunk[6]), chunk[5]
self.y = chunk[0]
def __eq__(self, other):
return (self.x==other.x) and (self.y==other.y)
def __lt__(self, other):
if self.x != other.x:
return self.x < other.x
return self.y > other.y
Now,
lis = sorted([lsDataSorted[i:i+8]
for i in range(0,len(lsDataSorted),8)],
key=Compare, reverse=True)
should give you the mixed complex sorting you're apparently looking for.
Upvotes: 4