Python将列表中的所有偶数相乘 [英] Python multiplying all even numbers in a list

查看:816
本文介绍了Python将列表中的所有偶数相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的第一个编程课程编写此python代码.昨天它部分起作用,但是后来我做了一些更改,现在仅通过了1个测试用例.目标是将列表"xs"中的所有偶数相乘,如果没有偶数则返回1.我在做什么错,我该如何解决?

I am working on this python code for my first programming class. Yesterday it partially worked but then I changed something and now it is only passing 1 test case. The goal is to multiply all even numbers in list "xs" and return 1 if there are no even numbers. What am I doing wrong and how can I fix it?

def evens_product(xs):
    product = 2
    for i in xs:
        if i%2 == 0:
            product *= i
            return product

    else:
        return (1) 

Chepner的解决方案对所有帮助过的人都表示感谢

Chepner's solution worked thank you to everyone who helped

推荐答案

由于两个原因,您需要初始化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

这篇关于Python将列表中的所有偶数相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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