用python写一个排序算法
: e7 F/ a9 V) X
$ k7 {0 x3 U4 {: _在 Python 中,可以使用内置的 sorted 函数来对列表进行排序。例如,要对数字列表进行升序排序,可以这样写: numbers = [3, 1, 4, 2]sorted_numbers = sorted(numbers)print(sorted_numbers) # 输出 [1, 2, 3, 4]如果要对字符串列表进行排序,可以使用 key 参数来指定排序的关键字,例如: strings = ['c', 'a', 'd', 'b']sorted_strings = sorted(strings, key=lambda s: s.lower())print(sorted_strings) # 输出 ['a', 'b', 'c', 'd']还可以使用 reverse 参数来指定是升序还是降序排列,例如: numbers = [3, 1, 4, 2]sorted_numbers = sorted(numbers, reverse=True)print(sorted_numbers) # 输出 [4, 3, 2, 1]如果要实现自定义的排序算法,可以使用 Python 的 sort 方法,例如: numbers = [3, 1, 4, 2]numbers.sort()print(numbers) # 输出 [1, 2, 3, 4]也可以使用 key 参数来指定排序的关键字,例如: strings = ['c', 'a', 'd', 'b']strings.sort(key=lambda s: s.lower())print(strings) # 输出 ['a', 'b', 'c', 'd']还可以使用 reverse 参数来指定是升序还是降序排列,例如: numbers = [3, 1, 4, 2]numbers.sort(reverse=True)print(numbers) # 输出 [4, 3, 2, 1]复制代码注意,使用 sort 方
% f& X. ]/ Y# Q X6 b- G d
4 ?& i c8 }5 l) w6 ~/ t4 s4 _ |