[英]How to numerically sort list of strings containing numbers?
f1 = open("leader")
lines = f1.readlines()
lines.sort(key=int, reverse=True)
f1.close()
print(lines)
使用外部文件值:
345345:player7
435:zo
345:name
23:hello
1231:football
這是為了對它們進行排序,以便整數排序而不是名稱
IIUC:
l = ['345345:player7',
'435:zo',
'345:name',
'23:hello',
'1231:football']
sorted(l, key=lambda x: int(x.split(':')[0]))
輸出:
['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']
排序鍵應該:“拆分一次,轉換為整數”。 不轉換為整數失敗,因為然后使用詞典比較,在那種情況下"10" < "2"
,而不是你想要的。
l = ['345345:player7',
'435:zo',
'345:name',
'23:hello',
'1231:football']
result = sorted(l, key=lambda x: int(x.split(':',1)[0]))
結果:
['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']
這不能處理數字相等的決勝局。 需要稍微復雜的排序鍵(但仍然可行)。 在這種情況下,刪除lambda
並創建一個實際函數,這樣你就可以執行split一次&unpack將第一部分轉換為整數:
def sortfunc(x):
number,rest = x.split(':',1)
return int(number),rest
result = sorted(l, key=sortfunc)
試試這個:(如果您還在從文件中讀取,則會很有幫助)
with open('leader.txt', mode = 'r') as f1:
data = f1.readlines()
# end with
keys = {}
output = []
for s in data:
num, value = s.split(sep=':')
if keys.get(int(num), False):
keys[int(num)].append(value)
else:
keys[int(num)] = [value]
for num in sorted(keys):
for i in keys[num]:
output.append((num, i))
for num, value in output:
print(f'{num}: {value}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.