python中sort()和sorted()排序函数用法详解

命运对每个人都是一样的,不一样的是各自的努力和付出不同,付出的越多,努力的越多,得到的回报也越多,在你累的时候请看一下身边比你成功却还比你更努力的人,这样,你就会更有动力。

导读:本篇文章讲解 python中sort()和sorted()排序函数用法详解,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

python中对数据的排序主要使用sort()和sorted()方法。

1、sort()方法

语法结构:

列表序列.sort( key=None, reverse=False)

注意: reverse 表示排序规则, reverse = True 降序, reverse = False 升序(默认)

示例代码1:

num_list1 = [1, 5, 2, 3, 6, 8]
num_list1.sort()
# 结果:[1, 2, 3, 5, 6, 8]
print(num_list1)

num_list2 = [1, 5, 2, 3, 6, 8]
num_list2.sort(reverse=True)
# 结果:[8, 6, 5, 3, 2, 1]
print(num_list2)

运行结果:

python中sort()和sorted()排序函数用法详解

示例代码2:

num_list1 = [("b", 2), ("a", 1), ("c", 5), ("d", 4)]

num_list1.sort()
print(num_list1)

num_list2 = [("b", 2), ("a", 1), ("c", 5), ("d", 4)]
num_list2.sort(key=lambda x: x[1], reverse=True)
print(num_list2)

运行结果:

python中sort()和sorted()排序函数用法详解

示例代码3:

students = [
    {'name': 'TOM', 'age': 20},
    {'name': 'ROSE', 'age': 19},
    {'name': 'Jack', 'age': 22}
]

students.sort(key=lambda x: x['name'], reverse=True)
print(students)

students.sort(key=lambda x: x['age'], reverse=True)
print(students)

运行结果:

python中sort()和sorted()排序函数用法详解

2、sorted()方法

语法结构:

sorted(*args, **kwargs)

示例代码1:

num_list1 = [1, 5, 2, 3, 6, 8]
ret = sorted(num_list1)
print(num_list1)
print(ret)

print("*" * 100)

num_list2 = [1, 5, 2, 3, 6, 8]
ret2 = sorted(num_list2, reverse=True)
print(num_list2)
print(ret2)

运行结果:

python中sort()和sorted()排序函数用法详解

示例代码2:

num_list1 = [("b", 2), ("a", 1), ("c", 5), ("d", 4)]

ret = sorted(num_list1)
print(num_list1)
print(ret)

print("*" * 100)

num_list2 = [("b", 2), ("a", 1), ("c", 5), ("d", 4)]
ret2 = sorted(num_list2, key=lambda x: x[1], reverse=True)
print(ret2)

print("*" * 100)

num_list3 = [("b", 2), ("a", 1), ("c", 5), ("d", 4)]
ret3 = sorted(map(lambda x: x[1], num_list3), reverse=True)
print(ret3)

运行结果:

python中sort()和sorted()排序函数用法详解

示例代码3:

students = [
    {'name': 'TOM', 'age': 20},
    {'name': 'ROSE', 'age': 19},
    {'name': 'Jack', 'age': 22}
]

ret = sorted(students, key=lambda x: x['name'], reverse=True)
print(ret)

ret2 = sorted(students, key=lambda x: x['age'], reverse=True)
print(ret2)

运行结果;

python中sort()和sorted()排序函数用法详解

3、sort()和sorted()区别

  • sort 是应用在 list 上的方法,而sorted 可以对所有可迭代的对象进行排序操作,是python内置的全局方法;
  • sort是对原有列表进行操作,而sorted返回的是一个新的可迭代对象,不会改变原来的对象;
  • sort使用方法为list.sort(), 而sorted的使用方法为sorted(list)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/142853.html

(0)

相关推荐

发表回复

登录后才能评论
半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!