我有一個包含數字整數和字串值對的文本檔案我想按升序對它們進行排序,但我沒有得到正確
**文本檔案.txt **
87,Toronto
45,USA
45,PAKISTAN
33,India
38,Jerry
30,Tom
23,Jim
7,Love
38,Hate
30,Stress
我的代碼
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)
我的輸出
********* Sorting now **************
Toronto 87
Love 7
USA 45
PAKISTAN 45
Jerry 38
Hate 38
India 33
Tom 30
Stress 30
Jim 23
預期產出
********* Sorting now **************
Toronto 87
USA 45
PAKISTAN 45
Jerry 38
Hate 38
India 33
Tom 30
Stress 30
Jim 23
Love 7
在輸出的第 2 行有錯誤,它應該在最后
uj5u.com熱心網友回復:
您正在比較字串,而不是數字。
在字典中(比如物體書),單詞按誰的第一個字母“最低”排序,如果是平局,我們選擇最低的第二個字母,依此類推。這稱為字典順序。
所以字串“aaaa”<“ab”。此外,“1111”<“12”
要解決此問題,您必須將字串轉換為數字(在函式中使用int(s[0])而不是)。s[0]score.append
這將使 1111 > 12。您的代碼將給出正確的結果。
uj5u.com熱心網友回復:
您可以使用 Python 的sorted()函式對串列進行排序。如果使用該key引數,則可以指定自定義排序行為,如果使用該reverse引數,則可以按降序排序。
此外,您可以使用csv 模塊來更輕松地讀取輸入檔案。
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]}")
輸出:
Toronto 87
USA 45
PAKISTAN 45
Jerry 38
Hate 38
India 33
Tom 30
Stress 30
Jim 23
Love 7
uj5u.com熱心網友回復:
不確定你的意圖,但一個緊湊的實作就像:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524707.html
標籤:Python列表排序帮手
上一篇:如何按另一個id對laravel的elequent串列進行排序
下一篇:將元素移動到物件陣列的頂部
