Home > Mobile >  Sort lines and sublines start with same string
Sort lines and sublines start with same string

Time:04-03

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

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']

CodePudding user response:

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]))
  • Related