Chaban33
Chaban33

Reputation: 1382

Sort by 2 keys but reverse only first key

Asking again, because my questions was closed before I could make an update.

This is standard sorting by 2 keys and it reverses the result for both keys.

s = sorted(s, key = lambda x: (x['date'], x['id']), reverse=True)

but how can I do reverse only for the first key and if I need to sort by second key it should sort without reversing?

output now

ID DATE 
1282 2019-12-19 12:09:28 
1281 2019-12-19 12:09:28 
1280 2019-12-19 12:09:28 
1279 2019-12-19 12:09:27 
1278 2019-12-19 12:09:27 
1277 2019-12-19 12:09:27 
1275 2019-12-19 12:09:27

Desired output

1280 2019-12-19 12:09:28 
1281 2019-12-19 12:09:28 
1282 2019-12-19 12:09:28 
1275 2019-12-19 12:09:27 
1277 2019-12-19 12:09:27 
1278 2019-12-19 12:09:27 
1279 2019-12-19 12:09:27

Upvotes: 1

Views: 537

Answers (1)

Chris Doyle
Chris Doyle

Reputation: 12155

assuming your field is stored as string but contains only ids which contain only digits. Then you can do an inplace sort by converting the id to an int for the purpose of the sort, this wont change the underlying type of the data, just merely for deciding the sort order.

data = """1282 2019-12-19 12:09:28 
1281 2019-12-19 12:09:28 
1280 2019-12-19 12:09:28 
1279 2019-12-19 12:09:27 
1278 2019-12-19 12:09:27 
1277 2019-12-19 12:09:27 
1275 2019-12-19 12:09:27"""

s = []
for line in data.splitlines():
    ID, *date = line.split()
    s.append((ID, " ".join(date)))

print("###BEFORE###")
for item in s:
    print(item[0], item[1])

s.sort(key=lambda x: (x[1], -int(x[0])), reverse=True)

print("###AFTER###")
for item in s:
    print(item[0], item[1])

print(f'type of {s[0][0]} is still {type(s[0][0])}')

OUTPUT

###BEFORE###
1282 2019-12-19 12:09:28
1281 2019-12-19 12:09:28
1280 2019-12-19 12:09:28
1279 2019-12-19 12:09:27
1278 2019-12-19 12:09:27
1277 2019-12-19 12:09:27
1275 2019-12-19 12:09:27
###AFTER###
1280 2019-12-19 12:09:28
1281 2019-12-19 12:09:28
1282 2019-12-19 12:09:28
1275 2019-12-19 12:09:27
1277 2019-12-19 12:09:27
1278 2019-12-19 12:09:27
1279 2019-12-19 12:09:27
type of 1280 is still <class 'str'>

Upvotes: 2

Related Questions