按字母順序對 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']
如你所見,原始陣列沒有改變。
廣告