I have a text file containing number integer and string value pairs I want to sort them in ascending order but I am not getting it correct
**TextFile.txt **
87,Toronto
45,USA
45,PAKISTAN
33,India
38,Jerry
30,Tom
23,Jim
7,Love
38,Hate
30,Stress
My code
def sort_outputFiles():
print('********* Sorting now **************')
my_file = open("TextFile.txt", "r",encoding='utf-8')
data = my_file.read()
data_into_list = data.split("\n")
my_file.close()
score=[]
links=[]
for d in data_into_list:
if d != '':
s=d.split(',')
score.append(s[0])
links.append(s[1])
n = len(score)
for i in range(n):
for j in range(0, n-i-1):
if score[j] < score[j+1]:
score[j], score[j+1] = score[j+1], score[j]
links[j], links[j+1] = links[j+1], links[j]
for l,s in zip(links,score):
print(l," ",s)
My output
********* Sorting now **************
Toronto 87
Love 7
USA 45
PAKISTAN 45
Jerry 38
Hate 38
India 33
Tom 30
Stress 30
Jim 23
Expected output
********* Sorting now **************
Toronto 87
USA 45
PAKISTAN 45
Jerry 38
Hate 38
India 33
Tom 30
Stress 30
Jim 23
Love 7
having error at line 2 in out put it should be in last
>Solution :
You are comparing strings, not numbers.
In an dictionary (like, the physical book), the words are sorted by who has the "lowest" first letter, and if it’s a tie, we pick the lowest second letter, and so on. This is called lexicographical order.
So the string "aaaa" < "ab". Also, "1111" < "12"
To fix this, you have to convert the string to a number (using int(s[0]) instead of s[0] in the score.append function).
This will make 1111 > 12. Your code will give the correct result.