列表的 sort()
方法对列表元素进行排序。
示例
prime_numbers = [11, 3, 7, 5, 2]
# sort the list in ascending order
prime_numbers.sort()
print(prime_numbers)
# Output: [2, 3, 5, 7, 11]
sort() 语法
numbers.sort(reverse, key)
sort()
方法可以接受两个可选的关键字参数
- reverse - 默认为
False
。如果传递True
,列表将按降序排序。 - key - 比较基于此函数。
降序排序
我们可以通过将 reverse
设置为 True
来将列表按降序排序。
numbers = [7, 3, 11, 2, 5]
# reverse is set to True
numbers.sort(reverse = True)
print(numbers)
输出
[11, 7, 5, 3, 2]
对字符串列表进行排序
sort()
方法按字典顺序对字符串列表进行排序。
cities = ["Tokyo", "London", "Washington D.C"]
# sort in dictionary order
cities.sort()
print(f"Dictionary order: {cities}")
# sort in reverse dictionary order
cities.sort(reverse = True)
print(f"Reverse dictionary order: {cities}")
输出
Dictionary order: ['London', 'Tokyo', 'Washington D.C'] Reverse dictionary order: ['Washington D.C', 'Tokyo', 'London']
根据长度倒序排列字符串
sort()
方法可以根据函数对项进行排序。例如,
text = ["abc", "wxyz", "gh", "a"]
# stort strings based on their length
text.sort(key = len)
print(text)
输出
['a', 'gh', 'abc', 'wxyz']
len
是一个内置函数,它返回字符串的长度。
由于我们将 len
函数作为 key
传递,因此字符串会根据其长度进行排序。