📌  相关文章
📜  在Python按字典顺序对单词进行排序(1)

📅  最后修改于: 2023-12-03 15:37:38.857000             🧑  作者: Mango

在Python按字典顺序对单词进行排序

在Python中对单词进行排序,可以使用列表的sort()方法或sorted()函数。根据字典顺序排序,可以使用默认的字符串比较方式,即将单词按照ASCII码的大小进行比较。下面是代码片段:

words = ["apple", "banana", "cherry", "date"]
words.sort()
print(words) # ['apple', 'banana', 'cherry', 'date']

words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words)
print(sorted_words) # ['apple', 'banana', 'cherry', 'date']

以上两种方法的输出结果相同,均按照字典顺序排序。如果需要按照其他方式排序,可以使用关键字参数key,指定一个函数来选择排序的关键字。下面是按照单词长度排序的代码片段:

words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=len)
print(sorted_words) # ['date', 'apple', 'banana', 'cherry']

在这个例子中,我们使用了len函数来选择排序的关键字,即单词的长度。这样,输出结果就是按照单词长度排序。

需要注意的是,sort()方法和sorted()函数均会修改原列表或生成一个新的排好序的列表。如果需要保留原列表,可以使用列表切片进行复制。例如:

words = ["apple", "banana", "cherry", "date"]
sorted_words = words[:]
sorted_words.sort()
print(words) # ['apple', 'banana', 'cherry', 'date']
print(sorted_words) # ['apple', 'banana', 'cherry', 'date']

这样,原列表words就不会被修改。