如何在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']
阅读更多:Python 教程
极客教程