简体   繁体   English

如何在不等于参数的列表中添加数字?

[英]How do I add numbers in a list that do not equal parameters?

I am trying to write a function that will add all of the numbers in a list that do not equal the parameters.我正在尝试编写一个函数,该函数将添加列表中不等于参数的所有数字。 The code I have, that is not working, is:我的代码不起作用,是:

def suminout(nums,a,b):
    total=0
    for i in range(len(nums)):
        if nums[i]!=a or nums[i]!=b:
            total=total+nums[i]
    return total

It appears to be summing everything in the list.它似乎在总结列表中的所有内容。

For example, if I called: suminout([1,2,3,4],1,2) it should return 7. However, I am getting 10.例如,如果我调用: suminout([1,2,3,4],1,2) 它应该返回 7。但是,我得到 10。

Any thoughts?有什么想法吗?

As Kasramvd so duly noted, you need conjunction not disjunction.正如 Kasramvd 充分指出的那样,您需要连接而不是分离。

Here is a list comprehension doing the same thing.这是一个做同样事情的列表理解。

def suminout(nums, a, b):
    total = 0
    total = sum([x for x in nums if (x!=a and x!=b)])
    return total

You need to use and instead of or .您需要使用and而不是or

def suminout(nums,a,b):
    total=0
    for i in range(len(nums)):
        if nums[i]!=a and nums[i]!=b:
            total=total+nums[i]
    return total

Your for logic could be further simplified (without using len() and range() ) as:您的for逻辑可以进一步简化(不使用len()range() )为:

for num in nums:
    if num not in [a, b]:  # same as: num != a and num != b
        total += num  # same as: total = total + num

Better way to achieve it using list comprehension with sum() as mentioned by Sean.使用 Sean 提到的sum() list comprehension来实现它的更好方法。 OR you may use filter() instead of list comprehension:或者您可以使用filter()而不是列表理解:

>>> my_list = [1, 2, 3, 4]
>>> sum(filter(lambda x: x !=1 and x!=4, my_list))
5

Or:或者:

def suminout(nums, a, b):
    total = 0
    total = sum([x for x in nums if x not in (a,b)])
    return total

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

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