仅对列表中包含的数字求和 [英] summing only the numbers contained in a list

查看:138
本文介绍了仅对列表中包含的数字求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一种对list中所有数字求和的方法.该方法应该能够跳过不是数字的元素.因此,sum([1, 2, 3])应该是6,但是sum(['A', 1, 'B', 2, 3]) 也应该6.我该怎么做?

Give a method that sums all the numbers in a list. The method should be able to skip elements that are not numbers. So, sum([1, 2, 3]) should be 6 but sum(['A', 1, 'B', 2, 3]) should also be 6. How can I accomplish this?

到目前为止我已经尝试过的:

What I have already tried so far:

def foo(list):
    dict = "ABCDEFGHIJKLMN"
    n = 0
    for i in range(0, len(list) - 1):
        if list[i].str in dict:
            ""
        else:    
            n= n + list[i]
    return n

print foo([1, 2, 3, 4, 5, 6, "A", "B"])

推荐答案

您可以使用一个简单的衬纸来完成此操作:

You can do this with a simple one liner:

l1 = [1, 2, 3, 'A']

sum(filter(lambda i: isinstance(i, int), l1))
# prints 6

或者,如果需要在函数中使用它:

Or, if you need it inside a function:

def foo(l1):
    return sum(filter(lambda i: isinstance(i, int), l1))

此外,如注释中所述,请勿为变量使用dictlist之类的名称; *它们将遮盖字典(dict)和(list)类型的内置名称.然后,您需要明确地del dict, list以便按预期使用它们.

Additionally, as noted in the comments, don't use names like dict and list for your variables; *they will shadow they build-in names for the dictionary (dict) and (list) types. You'll then need to explicitly del dict, list in order to use them as intended.

但是,让我解释一下. filter 的作用是在这里:

But, let me explain. What filter does is here is:

a):将函数作为第一个参数:

a) It takes a function as its first argument:

# this function will return True if i is an int
# and false otherwise
lambda i: isinstance(i, int)

,然后获取列表l1(第二个参数)中的每个元素,并根据该函数评估它是True还是False.

and then takes every element inside the list l1 (second argument) and evaluates whether it is True or False based on the function.

b)然后,filter本质上将过滤掉列表l1中不是int实例的所有对象(即函数为它们返回False).结果,对于像[1, 2, 3, 'A']的列表,过滤器将返回[1, 2, 3],然后将由

b) Then, filter will essentially filter out any objects inside list l1 that are not instances of int (i.e the function returns False for them). As a result, for a list like [1, 2, 3, 'A'] filter is going to return [1, 2, 3] which will then be summed up by sum().

一些例子:

foo([1, 2, 3, 'A'])
# 6

foo([1, 2, 3])
# 6

foo([1, 2, 3, 'HELLO', 'WORLD'])
# 6


轻微警告:

按原样,这不会汇总float值,而是将其删除(以及该情况下的任何其他数字类型).如果也需要,只需在lambda函数中添加float类型,如下所示:

As is, this doesn't sum up float values, it drops them (and any other numeric types for that case). If you need that too, simply add the float type in the lambda function as so:

lambda i: isinstance(i, (int, float))

现在,您的函数也对浮点数求和:

Now, your function sums floats too:

foo([1, 2, 3, 3.1,  'HELLO', 'WORLD'])
# 9.1

lambda函数中根据需要添加任何其他类型,以捕获所需的情况.

Add any other types as necessary in the lambda function to catch the cases that you need.

无所不包:

@Copperfield 所述,您可以使用

As noted by @Copperfield you can check for objects that are instances of any number by utilizing the numbers.Number abstract base class in the numbers module. This acts as a catch-all case for numeric values:

import numbers # must import
sum(filter(lambda i: isinstance(i, numbers.Number), l1))

也更简单,更快一点:

此外,如 @ShadowRanger 所述,自

Additionally, as noted by @ShadowRanger, and since lambda might not be the most comfortable construct for new users, one could simply use a generator expression (which is also faster) with sum to get the same exact result:

sum(val for val in l1 if isinstance(val, numbers.Number))

这篇关于仅对列表中包含的数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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