欢迎访问宙启技术站
智能推送

Python中的内置函数sorted的使用

发布时间:2023-07-04 19:55:58

Python中的内置函数sorted()用于对容器对象(如列表、元组、字典等)进行排序操作。该函数会返回一个新的有序容器,不改变原有容器的结构。

sorted()函数的使用方法如下:

1. 对列表进行排序:sorted(list)

示例代码:

   nums = [4, 2, 1, 3]
   sorted_nums = sorted(nums)
   print(sorted_nums)
   

运行结果:

   [1, 2, 3, 4]
   

2. 对元组进行排序:sorted(tuple)

示例代码:

   student_scores = (("Alice", 85), ("Bob", 77), ("Charlie", 92))
   sorted_scores = sorted(student_scores, key=lambda score: score[1], reverse=True)
   print(sorted_scores)
   

运行结果:

   [('Charlie', 92), ('Alice', 85), ('Bob', 77)]
   

该示例中,使用了key参数和lambda表达式,指定了根据元组中的第二个元素(分数)进行降序排序。

3. 对字典进行排序:sorted(dict)

字典是无序的,所以排序字典主要是对字典的键或值进行排序。

示例代码:

   scores = {"Alice": 85, "Bob": 77, "Charlie": 92}
   sorted_keys = sorted(scores.keys())
   sorted_values = sorted(scores.values(), reverse=True)
   print(sorted_keys)
   print(sorted_values)
   

运行结果:

   ['Alice', 'Bob', 'Charlie']
   [92, 85, 77]
   

该示例中,分别对字典的键和值进行了排序。

4. 对字符串进行排序:sorted(str)

字符串是一个有序序列的特殊容器。可以直接对字符串进行排序。

示例代码:

   word = "python"
   sorted_word = sorted(word)
   print(sorted_word)
   

运行结果:

   ['h', 'n', 'o', 'p', 't', 'y']
   

sorted()函数的常用参数如下:

- key: 定义一个函数来指定排序的键。可以使用lambda表达式,也可以使用自定义的函数。

- reverse: 表示排序结果是升序还是降序。默认为False(升序)。