[英]Python how to sort a tuple (string, int) in numerical order for leaderboard
[英]Sort thru a file with int and string values in numerical order with python
我有一個具有以下值的文本文件:
username:password - number of daily visits: 15
username:password - number of daily visits: 482
username:password - number of daily visits: 4823
我想按從最高到最低的數字順序過濾文件,因此訪問次數最多的將位於文件的頂部,而最低的位於文件的末尾,我想這樣做但保留所有字符串值,所以它看起來像這樣:
username:password - number of daily visits: 4823
username:password - number of daily visits: 482
username:password - number of daily visits: 15
我設法做到了,但字符串值不會被維護,所以它只是:
4823
482
15
我真的不知道,我是初學者還在學習。
假設您總是在行尾有一個數字,您可以使用sorted
和自定義鍵:
with open('file.txt') as f, open('file2.txt', 'w') as f2:
f2.writelines(sorted(f.readlines(),
key=lambda s: int(s.rsplit(' ')[-1].strip()),
reverse=True))
輸入file.txt
:
username:password - number of daily visits: 15
username:password - number of daily visits: 482
username:password - number of daily visits: 4823
輸出file2.txt
:
username:password - number of daily visits: 4823
username:password - number of daily visits: 482
username:password - number of daily visits: 15
f.readlines()
[-1]
),確保沒有尾隨換行符( strip()
)並轉換為 int 來提取列表數字。sorted
,使用上面提取的數字作為鍵,使用相反的順序首先獲得更大的數字writelines
在新文件中寫入行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.