本文介绍了为什么sum()没有键arg?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我自动写了这样的东西:

Today, I automatically wrote some thing like this:

class Foo():
    def __init__(self, x):
        self.x = x

s = [Foo(1), Foo(2), Foo(3)]
sum_x = sum(s, key = lambda foo: foo.x)

得到了:

sum()没有 key arg有什么特殊原因吗?

Is there any special reason for sum() does not have a key arg?

推荐答案

因为您可以直接编写 sum(foo.x表示foo in s).如果您尝试使用确实带有 key 参数( sorted min max 等),该函数最终将返回键而不是原始项,并且在按键排序时获取原始项非常棘手,Python提供了一种内置的方式来执行此操作通过关键字参数.

Because you can just write sum(foo.x for foo in s) instead. If you tried to do this with one of the functions that does take a key argument (sorted, min, max, etc.), the function would end up returning the key(s) rather than the original item(s), and getting the original items while sorting by keys is tricky enough that Python gives you a built-in way to do that via a keyword argument.

因此: sum 没有带 key 的原因并没有特殊的原因;相反,这些其他功能有特殊的原因,为什么它们要做使用. key 是例外,而不是规则.

Thus: There's no special reason for sum to not take a key; rather, those other functions have special reasons why they do take a key. key is the exception, not the rule.

这篇关于为什么sum()没有键arg?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 20:16