您的位置: 网站首页> 大家问> 当前文章

python3中sort()和sorted()的区别

老董2019-09-15166围观,116赞

  在python3中sort()和sorted()都可以用来排序,二者有两个最主要的区别:

  1、sort只能应用在列表list上,而sorted可以对所有可迭代的对象进行排序的操作

  2、sort方法会在原list上直接进行排序,不会创建新的list。而sorted方法不会对原来的数据做任何改动,排序后的结果是新生成的。

  sort函数

  在python3中sort有key和reverse两个可选参数。

  list.sort( key=None, reverse=False)

  key -- 参数key指定了只含一个参数的方法,该方法的参数是取自于可迭代对象中,提取可迭代对象中的每一个元素进行排序。

  reverse -- 排序规则,reverse = True降序,reverse = False升序(默认)。

  1、通过元素长度排序

# -*- coding: utf-8 -*-


lis = ["bbb123","csecc","bac","ab5","ba"]
lis.sort(key=len)
print(lis)
D:python3installpython.exe D:/pyscript/py3script/python66/python66.py
['ba', 'bac', 'ab5', 'csecc', 'bbb123']

Process finished with exit code 0



  2、通过元素的字符顺序

# -*- coding: utf-8 -*-


lis = ["bbb123","csecc","bac","ab5","ba"]
lis.sort()
print(lis)
D:python3installpython.exe D:/pyscript/py3script/python66/python66.py
['ab5', 'ba', 'bac', 'bbb123', 'csecc']

Process finished with exit code 0



  3、更复杂一点的排序:list里的元素是一个字典,通过字典的某个属性值排序。

# -*- coding: utf-8 -*-

stu = [
    {"name":"a1", "age":18},
    {"name":"b1", "age":19},
    {"name":"c1", "age":17}
]

# 按照name排序
stu.sort(key = lambda x:x['name'])
print(stu)

# 按照age排序
stu.sort(key = lambda x:x['age'])
print(stu)
D:python3installpython.exe D:/pyscript/py3script/python66/python66.py
[{'name': 'a1', 'age': 18}, {'name': 'b1', 'age': 19}, {'name': 'c1', 'age': 17}]
[{'name': 'c1', 'age': 17}, {'name': 'a1', 'age': 18}, {'name': 'b1', 'age': 19}]

Process finished with exit code 0


  sorted函数

  所有可以迭代的对象都可以用sorted来进行排序,排序不会改变原来的对象。sorted接收3个参数:

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

  iterable是可迭代的对象,key和reverse与sort里的相同。

  典型应用:对字典的值进行排序

# -*- coding: utf-8 -*-


stu = {'小明':7,'大名':12,'中二':9}
new_stu = sorted(stu.items(),key=lambda x:x[1],reverse=True)
print(new_stu)

D:\python3\install\python.exe D:/pyscript/py3script/python66/python66.py
[('大名', 12), ('中二', 9), ('小明', 7)]

Process finished with exit code 0


很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会

文章评论

    python3中sort()和sorted()的区别文章写得不错,值得赞赏

站点信息

  • 网站程序:Laravel
  • 客服微信:a772483200