首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为现有排序函数添加键参数支持的修饰器

为现有排序函数添加键参数支持的修饰器
EN

Code Review用户
提问于 2018-12-22 08:54:44
回答 1查看 65关注 0票数 4

前言

sorted内建函数key关键字专用参数.大多数自定义实现都类似于堆排序算法的以下实现

代码语言:javascript
运行
复制
import heapq
import itertools
from typing import (Iterable,
                    TypeVar)

Domain = TypeVar('Domain')


def heapsort(iterable: Iterable[Domain]) -> Iterable[Domain]:
    heap = []
    for element in iterable:
        heapq.heappush(heap, element)
    for _ in itertools.repeat(None, len(heap)):
        yield heapq.heappop(heap)

不支持key参数。我想到了一个装饰器,它将在下一种方式中添加key参数支持。

代码语言:javascript
运行
复制
from functools import wraps
from operator import itemgetter
from typing import (Callable,
                    Iterable,
                    Optional,
                    TypeVar)

Domain = TypeVar('Domain')
Sortable = TypeVar('Sortable')


def with_key(plain: Callable[[Iterable[Sortable]], Iterable[Sortable]]
             ) -> Callable[..., Iterable[Domain]]:
    @wraps(plain)
    def implementation(iterable: Iterable[Domain],
                       *,
                       key: Optional[Callable[[Domain], Sortable]] = None
                       ) -> Iterable[Domain]:
        if key is None:
            yield from plain(iterable)
            return
        yield from map(itemgetter(2),
                       plain((key(element), index, element)
                             for index, element in enumerate(iterable)))

    return implementation

在那之后,就像

代码语言:javascript
运行
复制
>>> heapsort_with_key = with_key(heapsort)
>>> list(heapsort_with_key(range(10), key=lambda x: -x))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

问题

我想知道是否有更好的方法(例如,在内存效率方面)添加key参数?有人知道它是如何在sorted中实现的吗?

EN

回答 1

Code Review用户

发布于 2018-12-22 13:30:02

Python是开源的,GitHub存储库python/cpython中的所有源代码都是开源的。对于大量的内置程序,可以在cpython/Python/bltinmodule.c中找到它们。在当前的修订版中,排序函数定义的开始在第2175项中找到,实际的函数本身在第2201项中找到。

但是,我不确定了解排序的实现是否会对优化堆排序有太大帮助,因为排序使用蒂姆塞德

我可以提出一个建议:装饰师总是会增加开销,尤其是在这种情况下,最好只是将关键参数与原始函数集成起来,但这个答案可能忽略了问题的全部要点。

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/210160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档