1

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
Chaban33
  • 1,362
  • 11
  • 38
  • 1
    if the id field is an int just add a minus to it in the sort `s = sorted(s, key = lambda x: (x['date'], -x['id']), reverse=True)` – Chris Doyle Dec 19 '19 at 12:26
  • if its not an int then convert it in the sort `s = sorted(s, key = lambda x: (x['date'], -int(x['id'])), reverse=True) – Chris Doyle Dec 19 '19 at 12:27
  • @ChrisDoyle it is not possible to convert it to a int. I don't want to go into details but it is not possible. is there any other solution? – Chaban33 Dec 19 '19 at 12:31
  • [Related question with answers](https://stackoverflow.com/questions/37693373/sort-python-list-with-two-keys-but-only-one-in-reverse-order) – DarrylG Dec 19 '19 at 12:31
  • why cant you convert it as an int just in the sort, it wont change the underlying type of the value in the list – Chris Doyle Dec 19 '19 at 12:32

1 Answers1

2

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'>
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42