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
CodePudding user response:
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.
CodePudding user response:
You can use Python's sorted() function to sort the list. If you use the key
parameter, you can specify a custom sorting behaviour, and if you use the reverse
parameter, you can sort in descending order.
Also, you can use the csv module to make reading your input file easier.
import csv
with open("TextFile.txt", "r", encoding="utf-8", newline="") as csvfile:
lines = list(csv.reader(csvfile))
for line in sorted(lines, key=lambda l: int(l[0]), reverse=True):
print(f"{line[1]} {line[0]}")
Output:
Toronto 87
USA 45
PAKISTAN 45
Jerry 38
Hate 38
India 33
Tom 30
Stress 30
Jim 23
Love 7
CodePudding user response:
Not sure about your intentions, but a compact implementation would be like:
with open('textfile.txt', 'r') as f:
d = [l.split(',') for l in f.readlines()]
d=[(dd[1][:-1], int(dd[0])) for dd in d]
d_sorted = sorted(d, key=lambda x:x[1], reverse=True)
print(d_sorted)