在Python中按字典顺序对单词进行排序
按字典顺序对单词进行排序意味着我们要首先按单词的第一个字母排列它们。然后,对于第一个字母相同的单词,我们将它们按第二个字母排列在该组中,依此类推,就像在语言的词典中一样(不是数据结构)。
Python有2个函数,按照这种类型的顺序进行排序和排序,让我们看看如何以及何时使用这些方法。
就地排序:当我们要对数组/列表进行就地排序时,即更改当前结构本身的顺序时,可以直接使用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']
如您所见,原始数组未更改。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下