python元组的创建取值排序计数_从keyvalue对元组列表中获取计数最少的项的键

The goal is to find the last n keys with the least counts

根据这个目标的定义,你的两个解决方案都不适合。在一个带有Counter的程序中,您使用dict,这将使键的顺序未定义,您将不会得到最后一个键,而是一些值最小的n键。第二个解决方案有不正确的切片,如果它被修复,它将返回值最小的第一个n键。在

考虑到^{}实现是stable,可以像这样重写它以符合目标:def author_2():

output, *_ = zip(*sorted(reversed(l), key=lambda v: v[1])[:n])

return list(reversed(output))

但是使用^{}是一个更好的主意,这是一个stdlib工具,用于处理“来自iterable的n个最小/最大值”(正如Martijn Pieters所指出,nlargest和{}也是稳定的,文档确实是这样说的,但是是隐式的)。尤其是如果你要处理的真正的列表是大的(对于小的n它应该比sorted作为docs describe)更快。在

^{pr2}$

您可以进一步提高性能,但以顺序(排序稳定性)为代价,即一些值最小的n键代替最后一个值最小的n键。为此,您需要保留一个“heapified”列表,并将其用作内部数据结构,而不是普通的list(如果您不更改列表并且只需要bottom-n一次,它将不会提高性能)。您可以从列表中推送和弹出,例如:_p2_heap = None

def prop_2():

global _p2_heap

if not _p2_heap:

_p2_heap = []

for item in l:

heapq.heappush(_p2_heap, item[::-1])

return [item[1] for item in heapq.nsmallest(n, _p2_heap)]

下面是完整的模块,您可以使用它来对解决方案进行基准测试。在import heapq

from collections import Counter

l = [

('herr', 1), ('dapao', 1),

('cino', 1), ('o', 38),

('tiao', 2), ('tut', 1),

('poh', 6), ('micheal', 1),

('orh', 1), ('horlick', 3),

('si', 1), ('tai', 1),

('titlo', 1), ('siew', 17),

('da', 1), ('halia', 2)

]

n = 5

def author_1():

return list(dict(Counter(dict(l)).most_common()[-n:]).keys())

def author_2():

output, *_ = zip(*sorted(reversed(l), key=lambda v: v[1])[:n])

return list(reversed(output))

def prop_1():

rev_result = heapq.nsmallest(n, reversed(l), key=lambda v: v[1])

return [item[0] for item in rev_result][::-1]

_p2_heap = None

def prop_2():

global _p2_heap

if not _p2_heap:

_p2_heap = []

for item in l:

heapq.heappush(_p2_heap, item[::-1])

return [item[1] for item in heapq.nsmallest(n, _p2_heap)][::-1]

以下是timeit结果:$ python -m timeit -s "import tst" "tst.author_1()"

100000 loops, best of 3: 7.72 usec per loop

$ python -m timeit -s "import tst" "tst.author_2()"

100000 loops, best of 3: 3.7 usec per loop

$ python -m timeit -s "import tst" "tst.prop_1()"

100000 loops, best of 3: 5.51 usec per loop

$ python -m timeit -s "import tst" "tst.prop_2()"

100000 loops, best of 3: 3.96 usec per loop

但是,如果我们使l = l * 1000的话,差别将变得明显:$ python -m timeit -s "import tst" "tst.author_1()"

1000 loops, best of 3: 263 usec per loop

$ python -m timeit -s "import tst" "tst.author_2()"

100 loops, best of 3: 2.72 msec per loop

$ python -m timeit -s "import tst" "tst.prop_1()"

1000 loops, best of 3: 1.65 msec per loop

$ python -m timeit -s "import tst" "tst.prop_2()"

1000 loops, best of 3: 767 usec per loop

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值