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

Python中的sorted()函数用法及案例

发布时间:2023-07-06 06:14:08

Python中的sorted()函数是一种用于对可迭代对象进行排序的内置函数。它返回一个经过排序后的新的列表,而不影响原始列表。

sorted(iterable, key=None, reverse=False)

参数:

- iterable:表示可迭代对象,如列表、元组、字符串等。

- key:表示可选参数,用于指定排序的函数。

- reverse:表示可选参数,指定是否降序排序,默认为升序排序。

下面是一些使用sorted()函数的案例:

1. 对列表进行排序:

numbers = [5, 1, 8, 2, 6]

sorted_numbers = sorted(numbers)

print(sorted_numbers)

# 输出:[1, 2, 5, 6, 8]

2. 对字符串进行排序:

string = "python"

sorted_string = sorted(string)

print(sorted_string)

# 输出:['h', 'n', 'o', 'p', 't', 'y']

3. 对元组进行排序:

tuple = (5, 1, 8, 2, 6)

sorted_tuple = sorted(tuple)

print(sorted_tuple)

# 输出:[1, 2, 5, 6, 8]

4. 使用key参数进行自定义排序:

names = ["Alice", "bob", "Charlie", "dave"]

sorted_names = sorted(names, key=str.lower)

print(sorted_names)

# 输出:['Alice', 'bob', 'Charlie', 'dave']

5. 使用reverse参数进行降序排序:

numbers = [5, 1, 8, 2, 6]

sorted_numbers = sorted(numbers, reverse=True)

print(sorted_numbers)

# 输出:[8, 6, 5, 2, 1]

6. 对字典进行排序:

students = {"Alice": 75, "Bob": 82, "Charlie": 90, "Dave": 67}

sorted_students = sorted(students.items(), key=lambda x: x[1], reverse=True)

print(sorted_students)

# 输出:[('Charlie', 90), ('Bob', 82), ('Alice', 75), ('Dave', 67)]

在这个案例中,我们使用了sorted()函数对字典进行排序。sorted()函数的key参数被设置为一个lambda函数,它根据字典的值进行排序。通过将字典转换为元组,我们将键和值都包含在其中,然后进行排序。

总结:

sorted()函数是一个非常有用且灵活的排序函数。它可以用于对列表、元组、字符串等各种可迭代对象进行排序。通过使用key参数和reverse参数,我们可以对排序过程进行自定义。希望以上的解释和案例能对你理解和使用sorted()函数有所帮助。