sort file of multiple numbers with text behind them

Question:

good evening everyone, I would like to help specifically with the sort

the data is always on a different line and the text is behind the numbers

20:10:20 text
2:10:20 text
1:10:20 text
22:10:1 text
21:10:19 text
20:10:1 text

and they need to arrange it by numbers

so if the input is the example above, I expect the output to sort all numbers 0[2]

I am looking for this

1:10:20 text
2:10:20 text
20:10:1 text
20:10:20 text
21:10:19 text
22:10:1 text


with open ("1.txt") as f:
         unsolved = (f.read (). split ())
         sor = sorted(unsolved)
for unsolved_elem in sor:

the problem is that it gives the result in the wrong order

enter image description here

Can someone help me with this? thanks to all for your help

Asked By: Nobikk

||

Answers:

Problem is that you compare strings and it compars char by char using char’s code – so it comapars strings "20" and "2:", not integer values 20 and 2 – and char "0" is before char ":" because "0" has code 48 and ":" has code 58.

You have to first split string "1:10:20 text" to tuple/list of strings ("1", "10", "20", "text") and later convert numbers to integers (1, 10, 20, "text") – and it will sort it correctly.

I use io to create file in memory – so everyone can simply copy and test it – but you should use open()

data = '''20:10:20 text
2:10:20 text
1:10:20 text
22:10:1 text
21:10:19 text
20:10:1 text'''

import io

# --- create tuples ---

rows = []

#with open('11000.txt', 'r', encoding='ISO-8859-1') as r:
with io.StringIO(data) as r:    
    for line in r:
        line = line.strip()  # remove `n` at the end
        numbers, text = line.split(' ')  # split 
        numbers = numbers.split(':')     # split numbers

        rows.append( [int(numbers[0]),int(numbers[1]),int(numbers[2]), line] )

# --- sorting ---

for row in sorted(rows):
   print(row[-1])
Answered By: furas
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.