掌握排序的艺术:Python中sorted()函数全面解析!
    		       		warning:
    		            这篇文章距离上次修改已过447天,其中的内容可能已经有所变动。
    		        
        		                
                
# 使用Python内置的sorted()函数对列表进行排序
 
# 原地排序,返回None
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort()
print(numbers)  # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
 
# 返回一个新的排序列表,原列表不变
numbers_copy = sorted(numbers)
print(numbers_copy)  # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
 
# 使用key参数进行自定义排序
strings = ['apple', 'banana', 'cherry']
strings_sorted = sorted(strings, key=len)
print(strings_sorted)  # 输出:['apple', 'cherry', 'banana']
 
# 使用reverse参数进行逆序排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers_rev = sorted(numbers, reverse=True)
print(numbers_rev)  # 输出:[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
 
# 使用sorted()函数处理字典的键或值
# 排序字典的键
d = {'banana': 3, 'apple': 4, 'mango': 1, 'cherry': 5}
sorted_keys = sorted(d.keys)
print(sorted_keys)  # 输出:['apple', 'banana', 'cherry', 'mango']
 
# 排序字典的值
sorted_items = sorted(d.items(), key=lambda item: item[1])
print(sorted_items)  # 输出:[('mango', 1), ('banana', 3), ('cherry', 5), ('apple', 4)]这段代码展示了如何使用Python内置的sorted()函数进行各种排序操作,包括原地排序和返回新列表的排序,以及如何使用key和reverse参数来自定义排序行为。同时,它也展示了如何对字典的键和值进行排序。
评论已关闭