以詞典順序對 Python 中的單詞進行排序


以詞典順序對單詞進行排序意味著我們想先按單詞的第一個字母對它們進行排列。然後,對於第一個字母相同的單詞,我們按第二個字母對它們進行排序,依此類推,就像在語言詞典(不是資料結構)中一樣。

Python 有 2 個函式,sort 和 sorted 用於此類順序,讓我們瞭解如何以及何時使用這些方法中的每一個。

就地排序:當我們希望對陣列/列表就地排序時,即,更改當前結構本身中的順序,我們可以直接使用 sort 方法。例如,

my_arr = [
"hello",
"apple",
"actor",
"people",
"dog"
]

print(my_arr)
my_arr.sort()
print(my_arr)

這將產生輸出 −

['hello', 'apple', 'actor', 'people', 'dog']
['actor', 'apple', 'dog', 'hello', 'people']

您在此處可以看到,原始陣列 my_arr 已被修改。如果您想保持此陣列不變,並在排序時建立一個新陣列,則可以使用 sorted 方法。例如,

示例

 現場演示

my_arr = [
"hello",
"apple",
"actor",
"people",
"dog"
]

print(my_arr)
# Create a new array using the sorted method
new_arr = sorted(my_arr)

print(new_arr)
# This time, my_arr won't change in place, rather, it'll be sorted
# and a new instance will be assigned to new_arr
print(my_arr)

輸出

這將產生輸出 −

['hello', 'apple', 'actor', 'people', 'dog']
['actor', 'apple', 'dog', 'hello', 'people']
['hello', 'apple', 'actor', 'people', 'dog']

正如您在此處所看到的,原始陣列沒有改變。

更新日期:20-06-2020

3K+ 瀏覽量

開始您的職業生涯

完成課程獲得認證

開始
廣告