gpt4 book ai didi

python - "lambda"vs. "operator.attrgetter(' xxx ')"作为排序键函数

转载 作者:IT老高 更新时间:2023-10-28 22:12:26 28 4
gpt4 key购买 nike

我正在查看一些使用比较函数进行大量排序调用的代码,它似乎应该使用关键函数。

如果您要更改 seq.sort(lambda x, y: cmp(x.xxx, y.xxx)),这是更可取的:

seq.sort(key=operator.attrgetter('xxx'))

或:

seq.sort(key=lambda a: a.xxx)

我也有兴趣对对现有代码进行更改的优点发表评论。

最佳答案

当纯粹在 attrgetter('attributename')lambda o: o.attributename 作为排序键之间选择时,然后使用 attrgetter() 是两者中更快的选项。

记住key函数只对列表中的每个元素应用一次,在排序之前,所以要比较两者,我们可以直接在计时赛中使用它们:

>>> from timeit import Timer
>>> from random import randint
>>> from dataclasses import dataclass, field
>>> @dataclass
... class Foo:
... bar: int = field(default_factory=lambda: randint(1, 10**6))
...
>>> testdata = [Foo() for _ in range(1000)]
>>> def test_function(objects, key):
... [key(o) for o in objects]
...
>>> stmt = 't(testdata, key)'
>>> setup = 'from __main__ import test_function as t, testdata; '
>>> tests = {
... 'lambda': setup + 'key=lambda o: o.bar',
... 'attrgetter': setup + 'from operator import attrgetter; key=attrgetter("bar")'
... }
>>> for name, tsetup in tests.items():
... count, total = Timer(stmt, tsetup).autorange()
... print(f"{name:>10}: {total / count * 10 ** 6:7.3f} microseconds ({count} repetitions)")
...
lambda: 130.495 microseconds (2000 repetitions)
attrgetter: 92.850 microseconds (5000 repetitions)

因此应用 attrgetter('bar') 1000 次大约比 lambda 快 40 μs。这是因为调用 Python 函数有一定的开销,比调用诸如 attrgetter() 生成的原生函数要多。

这种速度优势也转化为更快的排序:

>>> def test_function(objects, key):
... sorted(objects, key=key)
...
>>> for name, tsetup in tests.items():
... count, total = Timer(stmt, tsetup).autorange()
... print(f"{name:>10}: {total / count * 10 ** 6:7.3f} microseconds ({count} repetitions)")
...
lambda: 218.715 microseconds (1000 repetitions)
attrgetter: 169.064 microseconds (2000 repetitions)

关于python - "lambda"vs. "operator.attrgetter(' xxx ')"作为排序键函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2705104/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com