简体   繁体   English

在给定条件奇数或偶数的情况下,如何对列表中的偶数或奇数求和?

[英]How to sum even or odd numbers in a list given the condition odd or even?

So the problem is asking me to return the sum of even or odd elements in a list given the condition odd or even.所以问题是要求我在给定条件奇数或偶数的情况下返回列表中偶数或奇数元素的总和。 So if the condition is odd, I have to return a list of all odd numbers.所以如果条件是奇数,我必须返回所有奇数的列表。 If the list is blank/the values do not match the condition, then return 0.如果列表为空白/值与条件不匹配,则返回 0。

This is what I have so far:这是我到目前为止所拥有的:

l = [1,2,3,4,5,6]

def conditionalSum(value, condition):
    s = 0
    if condition == "even":
        for i in l:
            if i % 2 == 0:
                s += i
    elif condition == "odd":
        for i in l:
            if i % 2 !=0:
                s = s+ i
    else:
        return 0

When I try to run this, nothing comes up - not even an error!当我尝试运行它时,什么都没有出现 - 甚至没有错误! Any help is appreciated任何帮助表示赞赏

your code can be modified to be more pythonic using a built-in sum function.可以使用内置sum function 将您的代码修改为更加 Pythonic。

l = [1, 2, 3, 4, 5, 6]

def conditionalSum(value, condition):
    if condition == "even":
        return sum(i for i in l if i % 2 == 0)

    elif condition == "odd":
        return sum(i for i in l if i % 2 == 1)

    else:
        return 0

print(conditionalSum(value, "even"))

Output: Output:

12

btw you have an unused variable value in your function conditionalSum顺便说一句,您的 function conditionalSum中有一个未使用的变量value

  1. you need to call the fonction: conditionalSum(l, "even") for instance你需要调用函数:conditionalSum(l, "even") 例如
  2. you don't return any value for the 2 conditions "even" and "odd".对于“偶数”和“奇数”这 2 个条件,您不会返回任何值。 Corrected code:更正的代码:
l = [1,2,3,4,5,6]

def conditionalSum(value, condition):
    s = 0
    if condition == "even":
        for i in value:
            if i % 2 == 0:
                s += i
    elif condition == "odd":
        for i in value:
            if i % 2 !=0:
                s += i
    return s

print(conditionalSum(l,"even"))
print(conditionalSum(l,"odd"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM