汇总列表中的元素 [英] Summing elements in a list

查看:79
本文介绍了汇总列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,我需要对列表中未定义数量的元素求和.该怎么做?

Here is my code, I need to sum an undefined number of elements in the list. How to do this?

l = raw_input()
l = l.split(' ')
l.pop(0)

我的输入:3 5 4 9 输入后,我通过l.pop(0)删除第一个元素. 在.split(' ')之后,我的列表是['5', '4', '9'],我需要对列表中的所有元素求和.

My input: 3 5 4 9 After input I delete first element via l.pop(0). After .split(' ') my list is ['5', '4', '9'] and I need to sum all elements in this list.

在这种情况下,总和为18.请注意,未定义元素数.

In this case the sum is 18. Please notice that number of elements is not defined.

推荐答案

您只需使用 sum()内置:

sum(your_list)

它将汇总所有数量的项目.示例:

It will sum as many number items as you have. Example:

my_list = range(10, 17)
my_list
[10, 11, 12, 13, 14, 15, 16]

sum(my_list)
91

针对您的具体情况:

对于您的数据,首先将数字转换为int,然后将数字求和:

For your data convert the numbers into int first and then sum the numbers:

data = ['5', '4', '9']

sum(int(i) for i in data)
18

这将适用于列表中未定义个元素(只要它们是数字")

This will work for undefined number of elements in your list (as long as they are "numbers")

如果数据为字符串格式,感谢@senderle的注释重新转换.

Thanks for @senderle's comment re conversion in case the data is in string format.

这篇关于汇总列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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