對字串數字列表進行數字排序
儘管Python sort() 函數很簡單,但在處理表示數字的字串時可能會產生誤導。如下面的程式碼片段所示,嘗試將這些字串轉換為整數然後對它們進行排序會產生不正確的結果:
list1 = ["1", "10", "3", "22", "23", "4", "2", "200"] for item in list1: item = int(item) list1.sort() print(list1)
輸出:
['1', '10', '2', '200', '22', '23', '3', '4']
要修正此問題,您必須實際將您的字串轉換為整數。這是修正後的程式碼:
list1 = ["1", "10", "3", "22", "23", "4", "2", "200"] list1 = [int(x) for x in list1] list1.sort()
這將輸出正確的數字順序:
['1', '2', '3', '4', '10', '22', '23', '200']
或者,如果您需要將元素保留為字串,您可以在sort 中使用key 參數()。此參數接受在比較每個元素之前調用的函數。鍵函數的返回值用於比較,而不是元素本身。
例如:
list1 = ["1", "10", "3", "22", "23", "4", "2", "200"] list1.sort(key=int)
或
list1 = sorted([int(x) for x in list1])
以上是如何在 Python 中對字串數字列表進行數字排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!