python3.6没有sorted函数吗_Python3.6内置函数(59)——sorted()

本文目录

英文文档

sorted()

小结

英文文档

Return a new sorted list from the items in iterable.

Has two optional arguments which must be specified as keyword arguments.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

sorted()

1. 函数功能对一个可迭代对象进行排序,返回一个排序后列表。

1

2

3>>> a = sorted ( 'dcabegf' )

>>> a # 返回结果是列表

[ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' ]

2. 函数调用时可以提供一个可选的命名参数key,它是一个方法,默认值是None,用来指定具体排序的算法;函数对可迭代对象每个元素使用key算法后再排序,返回的仍然是可迭代对象中的元素。

1

2

3

4

5

6

7

8>>> a = [ 'a' , 'b' , 'd' , 'c' , 'B' , 'A' ]

>>> a

[ 'a' , 'b' , 'd' , 'c' , 'B' , 'A' ]

>>> sorted (a ) # 默认按字符ascii码排序

[ 'A' , 'B' , 'a' , 'b' , 'c' , 'd' ]

>>> sorted (a ,key = str. lower ) # 转换成小写后再排序,'a'和'A'值一样,'b'和'B'值一样

[ 'a' , 'A' , 'b' , 'B' , 'c' , 'd' ]

3. 函数调用时可以提供一个可选的命名参数reverse,它的默认值是False,用来排序结果是否倒转。

1

2

3

4

5

6

7>>> a = sorted ( 'dcabegf' )

>>> a

[ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' ]

>>> a = sorted ( 'dcabegf' ,reverse = True ) # 排序结果倒置

>>> a

[ 'g' , 'f' , 'e' , 'd' , 'c' , 'b' , 'a' ]

小结

希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,我都希望你留言和我们进行交流、讨论。

欢迎关注微信公众号,谢谢大家支持:AiryData。

转载请注明:数据之美 Python3.6内置函数(59)——sorted()

喜欢 (0) or 分享 (0)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值