Python中的列表排序函数示例
Python中的列表排序函数是Python中最常用的功能之一。这个函数可以通过给定的参数将列表中的元素进行排序。有时候我们需要对列表里面的元素进行排序,然后再进行其他操作,而排序操作可以使用Python内置的sorted()函数。在这篇文章中,我们将会介绍Python中比较常用的实现排序的方法和一些例子。
Python自带的列表排序函数
在Python中,有一个内置的列表排序函数sort(),它可以完成将列表中的元素按照一定的规则进行排序的任务。
sort()函数接受两个可选的参数,reverse 和 key。
reverse:如果设为 True,则表示按照降序排列,否则按照升序排列。
key:它是一个函数,可以指定用哪个元素进行排序。默认是按照列表中的每个元素的ASCII码进行排序的。
例子1:按照升序排列
列表中有四个数字,现在需要按照升序排列。
num_list = [4,7,1,3] num_list.sort() print(num_list)
执行结果:
[1, 3, 4, 7]
例子2:按照降序排列
列表中有四个数字,现在需要按照降序排列。
num_list = [4,7,1,3] num_list.sort(reverse=True) print(num_list)
执行结果:
[7, 4, 3, 1]
例子3:使用key参数
如果需要使用自定义的排序规则,使用key参数。
按照字符串长度进行排序。通过使用len()函数获取字符串长度。
str_list = ["123", "12345", "1234", "1"] str_list.sort(key=lambda x: len(x)) print(str_list)
执行结果:
['1', '123', '1234', '12345']
使用textwrap.fill()函数返回每行有8个字符的字符串列表,并按照长度排序。
import textwrap long_text = "Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation. Its language constructs and object-oriented approach aim to help programmers to write clear, logical code for small and large-scale projects." short_text_list = textwrap.wrap(long_text, width=8) short_text_list.sort(key=len) print(short_text_list)
执行结果:
['Python', 'is an', 'Its', 'with its', 'use of', 'aim to', 'help', 'code for', 'small and', 'clear,', 'logical', 'large-', 'level', 'general-', 'purpose', 'program-', 'language.', 'design', 'philosophy', 'code', 'for', 'and', 'object-', 'oriented', 'approach', 'to', 'write', 'projects.']
其他常用的排序函数
1. sorted()
与sort()类似,在Python中还有一个函数sorted(),它可以对任意序列进行排序,无论是列表、元组、集合还是字符串。
该函数使用方法如下:
sorted(list, [reverse=False],[key=None])
其中,list为待排序的序列,reverse和key参数与sort()函数相同。它通过对原始数据进行复制的方式,返回已排序的新列表,而不更改原始列表。
例子4:使用sorted()函数
使用sorted()函数对上面例子3中的字符串列表进行排序。
按照字符串长度进行排序。
str_list = ["123", "12345", "1234", "1"] result = sorted(str_list, key=len) print(result)
执行结果:
['1', '123', '1234', '12345']
按照倒序排序。
str_list = ["123", "12345", "1234", "1"] result = sorted(str_list, reverse=True) print(result)
执行结果:
['12345', '1234', '123', '1']
2. operator模块
Python的operator模块包含了很多内置的运算符函数,可以帮助我们简化Python程序的书写。它也提供了一个itemgetter()函数,它可以用于获取对象的某一个域的值。
operator.itemgetter()函数可以获取对象的特定域的值。它只需要一个参数,用于表示需要获取哪一个域。然后我们可以根据这个域进行排序。
import operator
data = [
{"name": "John", "age": 25},
{"name": "Jane", "age": 30},
{"name": "Alex", "age": 20}
]
new_data1 = sorted(data, key=operator.itemgetter("name"))
new_data2 = sorted(data, key=operator.itemgetter("age"))
print(new_data1)
print(new_data2)
执行结果:
[{'age': 20, 'name': 'Alex'}, {'age': 30, 'name': 'Jane'}, {'age': 25, 'name': 'John'}]
[{'age': 20, 'name': 'Alex'}, {'age': 25, 'name': 'John'}, {'age': 30, 'name': 'Jane'}]
这里,new_data1根据对象的name属性进行排序,new_data2根据对象的age属性进行排序。
总结
本文主要介绍了Python中常用的列表排序函数sort()和其他常用的排序函数sorted(),以及Python内置的operator模块。sort()函数支持对list、tuple等数据类型进行排序,sorted()函数支持对所有序列类型(list、tuple、str、set)进行排序。operator模块提供了一系列内置的函数,可以用于简化Python程序的编码。我们可以根据实际需求选择不同函数进行操作。
