python里order_volume_Python内置函数(59)——sorted

英文文档:

sorted(iterable[, key][, reverse])

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).

说明:

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

>>> a = sorted('dcabegf')>>> a #返回结果是列表

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

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

>>> 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,用来排序结果是否倒转。

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

['a', 'b', 'c', 'd', 'e', 'f', 'g']>>> a = sorted('dcabegf',reverse = True) #排序结果倒置

>>>a

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来为您编写一个模拟 Python 内置函数 sorted() 的函数。代码如下: ```python def my_sorted(iterable, key=None, reverse=False): """ 模拟 Python 内置函数 sorted() :param iterable: 可迭代对象 :param key: 排序依据函数 :param reverse: 是否逆序排序 :return: 排序后的列表 """ # 将可迭代对象转为列表 result = list(iterable) # 如果没有指定排序依据函数,则按元素自身大小进行排序 if key is None: result.sort(reverse=reverse) else: # 使用排序依据函数进行排序 result.sort(key=key, reverse=reverse) return result ``` 这个函数接受三个参数: - `iterable`:需要排序的可迭代对象。 - `key`:排序依据函数,默认为 `None`,即按元素自身大小进行排序。 - `reverse`:是否逆序排序,默认为 `False`。 函数的返回值是排序后的列表。您可以使用如下方式来调用这个函数: ```python # 排序一个列表 my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_list = my_sorted(my_list) print(sorted_list) # 按元素的绝对值大小进行排序 sorted_list = my_sorted(my_list, key=abs) print(sorted_list) # 按元素的倒数进行排序 sorted_list = my_sorted(my_list, key=lambda x: 1/x) print(sorted_list) # 逆序排序 sorted_list = my_sorted(my_list, reverse=True) print(sorted_list) ``` 输出结果分别为: ``` [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1] [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1] ``` 请注意,这个函数并不会改变原来的可迭代对象,而是返回一个新的列表。同时,这个函数的实现方式与 Python 内置函数 sorted() 可能有所不同,但是它们的功能是相同的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值