Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort lines and sublines start with same string

I want to sort a text file from reverse dates and also for the same years (after | part) in an alphabetical order. I can sort with reverse option but it will be reverse alphabetical order and can sort with key lambda split but dates will be mixed.

Text file

2022 | t
2022 | p
2022 | b
2022 | a
2022 | q
2021 | l
2021 | h
2021 | f
2021 | c
2020 | a
2020 | b

Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

test = open("test.txt")
test = test.readlines()
test.sort(reverse=True)
print(test)

test = open("test.txt")
test = test.readlines()
test.sort(key=lambda x: x.split(' | ')[1])
print(test)

Output 1 (Dates sorted, but after dates reverse-alphabetically)

['2022 | t\n', '2022 | q\n', '2022 | p\n', '2022 | b\n', '2022 | a\n', '2021 | l\n', '2021 | h\n', '2021 | f\n', '2021 | c\n', '2020 | b', '2020 | a\n']

Output 2 (after dates sorted alphabetically, but dates mixed)

['2022 | a\n', '2020 | a\n', '2020 | b', '2022 | b\n', '2021 | c\n', '2021 | f\n', '2021 | h\n', '2021 | l\n', '2022 | p\n', '2022 | q\n', '2022 | t\n']

>Solution :

You can use a normal sort, but negate the year part of the input to sort that backwards:

test.sort(key=lambda x: (-int(x.split(' | ')[0]), x.split(' | ')[1]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading