如何在python中的列表中添加整数? [英] How do I add together integers in a list in python?

查看:2729
本文介绍了如何在python中的列表中添加整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个列表

x = [2, 4, 7, 12, 3]

我将使用哪个函数/进程将所有数字加在一起?

What function/process would I use to add all of the numbers together?

除了使用sum
()之外还有什么方法吗?

Is there any way other than using sum ()?

推荐答案

x = [2, 4, 7, 12, 3]
sum_of_all_numbers= sum(x)

或者你可以试试这个:

x = [2, 4, 7, 12, 3] 
sum_of_all_numbers= reduce(lambda q,p: p+q, x)

减少是一个在列表的每个元素上累积执行函数的方法。它可以执行任何功能,因此如果您定义自己的模数函数,它将在列表的每个元素上重复执行该功能。为了避免定义执行p + q的整个函数,您可以改为使用lambda函数。

Reduce is a way to perform a function cumulatively on every element of a list. It can perform any function, so if you define your own modulus function, it will repeatedly perform that function on each element of the list. In order to avoid defining an entire function for performing p+q, you can instead use a lambda function.

这篇关于如何在python中的列表中添加整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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