更新时间:2023-02-10 15:38:21
由于两个原因,您需要初始化product = 1
.一种,简单地说,您会得到错误的答案. evens_product([4])
应该返回4,而不是8.
第二,它使您不必将没有偶数的列表作为特例.如果没有偶数,则永远不要更改product
的值并将其保持不变.
You need to initialize product = 1
, for two reasons. One, simply put, you'll get the wrong answer. evens_product([4])
should return 4, not 8.
Two, it saves you from having to treat a list with no even numbers as a special case. If there are no even numbers, you never change the value of product
and return it unchanged.
def evens_product(xs):
product = 1
for i in xs:
if i%2 == 0:
product *= i
return product