为什么sum()没有键arg?

编程入门 行业动态 更新时间:2024-10-25 08:28:14
本文介绍了为什么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)

得到了:

TypeError:sum()不带关键字参数

TypeError: sum() takes no keyword arguments

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?

本文发布于:2023-11-24 03:38:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623837.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:sum   arg

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!