Pythonsorted函数-排序序列
发布时间:2023-07-25 13:06:46
Python中的sorted函数是用来对序列进行排序的函数。它可以对字符串、列表、元组等序列进行排序,并返回一个新的已排序的序列,而不会改变原有序列。
sorted函数的语法如下:
sorted(iterable, key=None, reverse=False)
其中,iterable是待排序的序列,可以是字符串、列表、元组等。
key是一个函数,用来指定排序的关键字。默认为None,表示不使用关键字排序。
reverse是一个布尔值,用来指定排序的顺序。默认为False,表示升序排序。
例如,对一个列表进行升序排序:
numbers = [3, 1, 5, 2, 4] sorted_numbers = sorted(numbers) print(sorted_numbers)
输出为:[1, 2, 3, 4, 5]
如果要进行降序排序,可以设置reverse=True:
numbers = [3, 1, 5, 2, 4] sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers)
输出为:[5, 4, 3, 2, 1]
如果希望按照元素的某个属性进行排序,可以使用key参数。key参数接受一个函数,用来指定排序的关键字。例如,以下代码按照字符串的长度进行排序:
strings = ["hello", "world", "python", "code"] sorted_strings = sorted(strings, key=lambda x: len(x)) print(sorted_strings)
输出为:['code', 'hello', 'world', 'python']
也可以按照元素的某个属性进行降序排序:
strings = ["hello", "world", "python", "code"] sorted_strings = sorted(strings, key=lambda x: len(x), reverse=True) print(sorted_strings)
输出为:['python', 'hello', 'world', 'code']
总结来说,Python的sorted函数是对序列进行排序的函数。它非常灵活,可以对各种类型的序列进行排序,并且可以按照升序或降序进行排序,也可以按照元素的某个属性进行排序。
