使用Python中的sorted()函数进行列表的排序
发布时间:2023-08-05 22:14:39
Python中的sorted()函数可用于对列表进行排序。sorted()函数会返回一个排序后的新列表,而不会改变原始列表的顺序。
sorted()函数可以接受一个可迭代对象作为输入,包括列表、元组和字符串等。下面是一些使用sorted()函数进行列表排序的示例:
1. 对一个整数列表进行升序排序:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] sorted_numbers = sorted(numbers) print(sorted_numbers) # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
2. 对一个字符串列表进行按照字母顺序排序:
fruits = ["apple", "banana", "cherry", "date"] sorted_fruits = sorted(fruits) print(sorted_fruits) # 输出:['apple', 'banana', 'cherry', 'date']
3. 对一个带有数字和字母的字符串列表进行按照字符串的长度排序:
words = ["hello", "python", "world", "is", "fun"] sorted_words = sorted(words, key=len) print(sorted_words) # 输出:['is', 'fun', 'hello', 'world', 'python']
在第三个示例中,sorted()函数的key参数被设置为len,表示会根据字符串的长度进行排序。
sorted()函数也可以接受一个reverse参数,当reverse参数为True时,将按照降序排序。下面是一个示例:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] sorted_numbers_reversed = sorted(numbers, reverse=True) print(sorted_numbers_reversed) # 输出:[9, 6, 5, 5, 4, 3, 3, 2, 1, 1]
在这个示例中,sorted()函数按照降序对列表进行了排序。
需要注意的是,sorted()函数对列表进行排序时,会创建一个新的列表对象,而不会直接修改原始列表的顺序。如果需要在原始列表上进行排序,可以使用列表的sort()方法。
以上就是使用Python中的sorted()函数进行列表排序的一些示例。sorted()函数非常灵活,可以根据需求使用不同的参数进行排序,很好地满足了对列表排序的需求。
