Counter的most_common方法的基础实现是什么?

时间:2019-04-16 19:50:06

标签: python-3.x counter pyi

我找到了一个具有以下定义的pyi文件

def most_common(self, n: Optional[int] = ...) -> List[Tuple[_T, int]]: ...

这怎么可能发生?列表没有定义,也没有实现?


只需在此处为关注者强调一些有价值的建议即可

列表是从输入模块导入的;它与列表不同。 .pyi文件不需要导入,因为从不执行存根文件。他们只需要语法上有效的Python

如果您使用未来导入注释,则无需导入类型即可使用List等。在.py文件中的函数注释中也可以,因为函数注释将被视为字符串文字。 (从Python 4开始,这将是默认行为。有关详细信息,请参见PEP563。)

1 个答案:

答案 0 :(得分:1)

您正在查看pyi文件,该文件仅用于注释。它永远不会由Python解释器执行。您可以通过阅读PEP484了解有关pyi文件的更多信息。

使用调试器,在调用most_common的行上放置一个断点,然后进入该方法。

Python 3.7实现。

...\Lib\collections\__init__.py

def most_common(self, n=None):
    '''List the n most common elements and their counts from the most
    common to the least.  If n is None, then list all element counts.

    >>> Counter('abcdeabcdabcaba').most_common(3)
    [('a', 5), ('b', 4), ('c', 3)]

    '''
    # Emulate Bag.sortedByCount from Smalltalk
    if n is None:
        return sorted(self.items(), key=_itemgetter(1), reverse=True)
    return _heapq.nlargest(n, self.items(), key=_itemgetter(1))

_heapq.nlargest(在...\Lib\heapq.py中)实现:

def nlargest(n, iterable, key=None):
    """Find the n largest elements in a dataset.

    Equivalent to:  sorted(iterable, key=key, reverse=True)[:n]
    """

    # Short-cut for n==1 is to use max()
    if n == 1:
        it = iter(iterable)
        sentinel = object()
        if key is None:
            result = max(it, default=sentinel)
        else:
            result = max(it, default=sentinel, key=key)
        return [] if result is sentinel else [result]

    # When n>=size, it's faster to use sorted()
    try:
        size = len(iterable)
    except (TypeError, AttributeError):
        pass
    else:
        if n >= size:
            return sorted(iterable, key=key, reverse=True)[:n]

    # When key is none, use simpler decoration
    if key is None:
        it = iter(iterable)
        result = [(elem, i) for i, elem in zip(range(0, -n, -1), it)]
        if not result:
            return result
        heapify(result)
        top = result[0][0]
        order = -n
        _heapreplace = heapreplace
        for elem in it:
            if top < elem:
                _heapreplace(result, (elem, order))
                top, _order = result[0]
                order -= 1
        result.sort(reverse=True)
        return [elem for (elem, order) in result]

    # General case, slowest method
    it = iter(iterable)
    result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]
    if not result:
        return result
    heapify(result)
    top = result[0][0]
    order = -n
    _heapreplace = heapreplace
    for elem in it:
        k = key(elem)
        if top < k:
            _heapreplace(result, (k, order, elem))
            top, _order, _elem = result[0]
            order -= 1
    result.sort(reverse=True)
    return [elem for (k, order, elem) in result]