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

Python中的列表排序函数sorted()的使用方法

发布时间:2023-05-23 13:17:05

Python中的列表排序函数sorted()是一种对列表元素进行排序的方法,能够将任意类型的列表按照某种规则进行排序。它不仅可以对数字、字符串等基本类型进行排序,还可以对自定义类型的列表进行排序。

sorted()函数的基本使用方式是在函数中传入需要排序的列表,然后按照指定的排序规则进行排序,最后返回排好序的结果。下面是一些sorted()函数的用法和实例。

1. 对数字类型的列表进行排序

将一个数字列表按从小到大排列:

nums = [2, 5, 3, 8, 1]

sorted_nums = sorted(nums)

print(sorted_nums)    # 输出[1, 2, 3, 5, 8]

将一个数字列表按从大到小排列:

nums = [2, 5, 3, 8, 1]

sorted_nums = sorted(nums, reverse=True)

print(sorted_nums)    # 输出[8, 5, 3, 2, 1]

2. 对字符串类型的列表进行排序

将一个字符串列表按字母顺序从小到大排列:

words = ['apple', 'banana', 'orange', 'pear']

sorted_words = sorted(words)

print(sorted_words)    # 输出['apple', 'banana', 'orange', 'pear']

将一个字符串列表按字母顺序从大到小排列:

words = ['apple', 'banana', 'orange', 'pear']

sorted_words = sorted(words, reverse=True)

print(sorted_words)    # 输出['pear', 'orange', 'banana', 'apple']

3. 对自定义类型的列表进行排序

可以通过在sorted()函数中传入一个key关键字参数来指定排序规则,用于排序的关键字可以是自定义类型的某个属性。下面是一个示例,按照人员姓名的首字母进行排序。

class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age

    def __str__(self):

        return self.name

people = [Person('Lucy', 25),

          Person('Bob', 30),

          Person('Alice', 20),

          Person('David', 35)]

sorted_people = sorted(people, key=lambda x: x.name[0])

for person in sorted_people:

    print(person)

# 输出: Alice Bob David Lucy

以上就是sorted()函数的基本用法和实例。值得注意的是,sorted()函数并不会改变原始列表的顺序,而是返回一个排好序的结果。如果要在原始列表中直接排序,可以调用列表的sort()方法,用法和sorted()函数类似。