max(),sum(),next() [英] max(), sum(), next()

查看:60
本文介绍了max(),sum(),next()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

空Python列表[]不知道它将包含的项目类型,所以这听起来很奇怪:


>> sum([])



0


因为[]可能是某个对象的空序列:


>> sum(s在[" a"," b"]中为s,如果len(s)2)



0


在这种情况下使用静态类型语言,您可以回答物品类型的

初始化值这个列表,正如我在D. / $
总和()中所做的那样。


这听起来像是一个更正确/更干净的事情:


> ;> max([])



Traceback(最近一次调用最后一次):

文件" ;< stdin>",第1行,在< module>

ValueError:max()arg是一个空序列


所以它可能是更好地使sum([])过于引发ValueError,在
Python 3 / 3.1中(如果这不是真的)。另一方面经常

我有这样的代码:


>> max(如果谓词(x),则可迭代的x的乐趣(x))



这可能会提高ValueError如果可迭代为空,如果其项目的

谓词总是为假,那么我试图避免使用

异常,我通常以正常循环,

'可读且快速:

max_value = smallvalue

for x in iterable:

如果谓词(x):

max_value = max(max_value,fun(x))


如果跑步速度很重要,我甚至可能用更正常的if / else替换max(max_value,

fun(x))。


可能的替代方法是将默认值添加到max( ),就像下一个()

内置的Python 2.6:


>> max((如果谓词(x),则迭代中的x的fun(x)),default = smallvalue)



如果没有项目可以计算最大值,则返回smallvalue。


再见,
bearophile

解决方案

< be ************ @ lycos.comwrote:


>空的Python列表[]不知道它将包含的项目的类型,所以这听起来很奇怪:


>>> sum([])


0


>> help(sum)



sum(...)

sum(sequence,start = 0)-value


>> sum(x范围(x)的范围(x))



Traceback(最近一次调用最后一次):

文件"< stdin>",第1行,< module>

TypeError:不支持的操作数类型+:''int''和''list''


>> sum((范围(x)中x的范围(x)),[])



[0,0,1,0,1,2,0,1,2,3]


....所以列表可能不知道是什么类型它包含,但总和

。如果你不说,那就是一个合理的猜测。并且

它*是*拒绝诱惑猜测的情况是

错误的事情:你会用多少钱来做任何事情

除了和数值之外?而且,对于其他每一种情况,
必须写入总和(...,0)是多么乏味?特别是

铭记:


>> sum (["," b"],"")



Traceback(最近一次调用最后一次):

文件"< stdin>",第1行,< module>

TypeError:sum()无法求和字符串[use'''' '.join(seq)代替]


-

\S - si *** @ chiark.greenend.org.uk - http://www.chaos.org.uk/~sion/

坦率地说,我对企鹅的某种方式没有任何感情

- Arthur C. Clarke

她的努力是什么?ddre hl?heddes b?ce bump bump bump


< blockquote> be************@lycos.com 写道:


空的Python列表[]不知道它将包含的物品的类型,所以这听起来很奇怪:


>>> sum([])



0


因为[]可能是某个对象的空序列:



你是正确的,总和可以用来对任意对象求和。

然而,在99.99%的情况下,你将汇总数值。

添加实数时,中性元素为零。 (X + 0 = X)它对于空序列返回零是非常合理的。


相同的方式,如果我们有一个prod()函数因为X * 1 = X,它应该返回一个

空序列。此操作的中性元素

是一个。


当然,这对于总结其他类型的对象并不好。但是如何使用


总和(L + [0])


或<如果是L:

如果L:

value = sum(L)

else:

value = 0


而不是sum(L)。


再一次,这是sum()在大多数情况下的用法,所以这个

行为是预期的行为。一个。


说服你的另一个论点:SQL中的sum()函数为空

行集在大多数关系数据库中返回零。


但当然它本来可以以不同的方式实现......我相信已经有过多的关于这个决定的讨论,

,目前的实施情况非常好,如果不是最好的话。


最好,


Laszlo


9月3日,8:18 * pm,Laszlo Nagy< gand ... @ shopzeus.comwrote:


bearophileH ... @ lycos.com写道:


空的Python列表[]不知道它将会是什么类型的物品

包含,所以这听起来很奇怪:


>> sum([])


0


因为[]可能是某个对象的空序列:



你是对的,总和可能是用于对任意对象求和。

但是,在99.99%的情况下,你将对数值求和。

当添加实数时,中性元素为零。 (X + 0 = X)它对于空序列返回零是非常合理的。


相同的方式,如果我们有一个prod()函数因为X * 1 = X,它应该返回一个

空序列。此操作的中性元素

是一个。


当然,这对于总结其他类型的对象并不好。但是如何使用


总和(L + [0])


或<如果是L:

如果L:

value = sum(L)

else:

value = 0


而不是sum(L)。


再一次,这是sum()在大多数情况下的用法,所以这个

行为是预期的行为。一个。


说服你的另一个论点:SQL中的sum()函数为空

行集在大多数关系数据库中返回零。


但当然它本来可以以不同的方式实现......我相信已经有过多的关于这个决定的讨论,

,目前的实施情况非常好,如果不是最好的话。



另一种方法是将起始值默认为无,即

意味着没有起始价值。目前它从开始

值开始,然后''添加'序列中的项目,但它可以

从第一项开始然后''添加'以下项目。

所以:


总和([1,2,3])= 6

sum([" a"," b"," c"])=" abc"


为了向后兼容,如果序列为空且开始

值为None然后返回0.


Empty Python lists [] don''t know the type of the items it will
contain, so this sounds strange:

>>sum([])

0

Because that [] may be an empty sequence of someobject:

>>sum(s for s in ["a", "b"] if len(s) 2)

0

In a statically typed language in that situation you may answer the
initializer value of the type of the items of the list, as I do in the
sum() in D.

This sounds like a more correct/clean thing to do:

>>max([])

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence

So it may be better to make the sum([]) too raise a ValueError, in
Python 3/3.1 (if this isn''t already true). On the other hand often
enough I have code like this:

>>max(fun(x) for x in iterable if predicate(x))

This may raise the ValueError both if iterable is empty of if the
predicate on its items is always false, so instead of catching
exceptions, that I try to avoid, I usually end with a normal loop,
that''s readable and fast:

max_value = smallvalue
for x in iterable:
if predicate(x):
max_value = max(max_value, fun(x))

Where running speed matters, I may even replace that max(max_value,
fun(x)) with a more normal if/else.

A possible alternative is to add a default to max(), like the next()
built-in of Python 2.6:

>>max((fun(x) for x in iterable if predicate(x)), default=smallvalue)

This returns smallvalue if there are no items to compute the max of.

Bye,
bearophile

解决方案

<be************@lycos.comwrote:

>Empty Python lists [] don''t know the type of the items it will
contain, so this sounds strange:

>>>sum([])

0

>>help(sum)

sum(...)
sum(sequence, start=0) -value

>>sum(range(x) for x in range(5))

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: ''int'' and ''list''

>>sum((range(x) for x in range(5)), [])

[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]

.... so the list might not know what type it contains, but sum
does. And if you don''t tell it, it makes a sensible guess. And
it *is* a case where refusing the temptation to guess is the
wrong thing: how many times would you use sum to do anything
other than sum numeric values? And how tedious would it be to
have to write sum(..., 0) for every other case? Particularly
bearing in mind:

>>sum(["a", "b"], "")

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() can''t sum strings [use ''''.join(seq) instead]

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomet se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump


be************@lycos.com wrote:

Empty Python lists [] don''t know the type of the items it will
contain, so this sounds strange:

>>>sum([])

0

Because that [] may be an empty sequence of someobject:

You are right in that sum could be used to sum arbitrary objects.
However, in 99.99% of the cases, you will be summing numerical values.
When adding real numbers, the neutral element is zero. ( X + 0 = X) It
is very logical to return zero for empty sequences.

Same way, if we would have a prod() function, it should return one for
empty sequences because X*1 = X. The neutral element for this operation
is one.

Of course this is not good for summing other types of objects. But how
clumsy would it be to use

sum( L +[0] )

or

if L:
value = sum(L)
else:
value = 0

instead of sum(L).

Once again, this is what sum() is used for in most cases, so this
behavior is the "expected" one.

Another argument to convince you: the sum() function in SQL for empty
row sets returns zero in most relational databases.

But of course it could have been implemented in a different way... I
believe that there have been excessive discussions about this decision,
and the current implementation is very good, if not the best.

Best,

Laszlo


On Sep 3, 8:18*pm, Laszlo Nagy <gand...@shopzeus.comwrote:

bearophileH...@lycos.com wrote:

Empty Python lists [] don''t know the type of the items it will
contain, so this sounds strange:

>>sum([])

0

Because that [] may be an empty sequence of someobject:


You are right in that sum could be used to sum arbitrary objects.
However, in 99.99% of the cases, you will be summing numerical values.
When adding real numbers, the neutral element is zero. ( X + 0 = X) It
is very logical to return zero for empty sequences.

Same way, if we would have a prod() function, it should return one for
empty sequences because X*1 = X. The neutral element for this operation
is one.

Of course this is not good for summing other types of objects. But how
clumsy would it be to use

sum( L +[0] )

or

if L:
value = sum(L)
else:
value = 0

instead of sum(L).

Once again, this is what sum() is used for in most cases, so this
behavior is the "expected" one.

Another argument to convince you: the sum() function in SQL for empty
row sets returns zero in most relational databases.

But of course it could have been implemented in a different way... I
believe that there have been excessive discussions about this decision,
and the current implementation is very good, if not the best.

An alternative would be for the start value to default to None, which
would mean no start value. At the moment it starts with the start
value and then ''adds'' the items in the sequence to it, but it could
start with the first item and then ''add'' the following items to it.
So:

sum([1, 2, 3]) =6
sum(["a", "b", "c"]) ="abc"

For backward compatibility, if the sequence is empty and the start
value is None then return 0.


这篇关于max(),sum(),next()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆