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

使用Python的sorted()函数来排序序列数据

发布时间:2023-07-01 18:50:50

sorted()函数是Python内置的排序函数,可以对序列数据进行排序。它可以作用于字符串、列表、元组等可迭代对象。

sorted()函数的基本用法是sorted(iterable, key=None, reverse=False),其中参数iterable代表要排序的可迭代对象,key代表排序的方式(默认为None,即按照元素自身的大小进行排序),reverse代表排序的顺序(默认为升序)。

下面是使用sorted()函数进行排序的一些例子:

1. 对列表进行升序排序:

lst = [5, 2, 8, 1, 9]
sorted_lst = sorted(lst)
print(sorted_lst)

输出:[1, 2, 5, 8, 9]

2. 对列表进行降序排序:

lst = [5, 2, 8, 1, 9]
sorted_lst = sorted(lst, reverse=True)
print(sorted_lst)

输出:[9, 8, 5, 2, 1]

3. 对字符串进行按照ASCII码值进行排序:

s = "hello world"
sorted_s = sorted(s)
print(sorted_s)

输出:[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

4. 对字典的键进行排序:

d = {'a': 5, 'b': 2, 'c': 8, 'd': 1}
sorted_keys = sorted(d.keys())
print(sorted_keys)

输出:['a', 'b', 'c', 'd']

5. 对自定义对象进行排序:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"

p1 = Person("Alice", 25)
p2 = Person("Bob", 30)
p3 = Person("Charlie", 20)

persons = [p1, p2, p3]
sorted_persons = sorted(persons, key=lambda x: x.age)
print(sorted_persons)

输出:[Person(name='Charlie', age=20), Person(name='Alice', age=25), Person(name='Bob', age=30)]

通过以上几个例子,我们可以看到sorted()函数可以对序列数据进行排序,不论是数字、字符串、列表、字典甚至是自定义对象,都可以使用sorted()函数轻松实现排序。