如何在 Python 中生成一個排序列表?


在 Python 中,列表的排序方法使用給定類的 gt 和 lt 運算元進行比較。大部分內建類中已經實現了這些運算元,所以它會自動提供已排序的列表。你可以按照如下方式使用它

words = ["Hello", "World", "Foo", "Bar", "Nope"]
numbers = [100, 12, 52, 354, 25]
words.sort()
numbers.sort()

print(words)
print(numbers)

這會給出一個輸出

['Bar', 'Foo', 'Hello', 'Nope', 'World']
[12, 25, 52, 100, 354]

如果你不想在原地將輸入列表排序,你可以使用 sorted 函式來實現。例如,

words = ["Hello", "World", "Foo", "Bar", "Nope"]
sorted_words = sorted(words)

print(words)
print(sorted_words)

這會給出一個輸出

["Hello", "World", "Foo", "Bar", "Nope"]
['Bar', 'Foo', 'Hello', 'Nope', 'World']

更新於: 17-Jun-2020

361 閱讀量

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.