对Python中的数字列表求和 [英] Sum a list of numbers in Python

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

问题描述

我有一个数字列表,例如[1,2,3,4,5...],我想计算(1+2)/2,对于第二个(2+3)/2和第三个, (3+4)/2,依此类推.我该怎么办?

我想将第一个数与第二个数相加并除以2,然后将第二个数与第三个数相加并除以2,依此类推.

而且,我该如何对数字列表求和?

a = [1, 2, 3, 4, 5, ...]

是吗

b = sum(a)
print b

得到一个号码?

这对我不起作用.

解决方案

问题1:因此,您想要(元素0 +元素1)/2,(元素1 +元素2)/2,...,等等.

我们列出两个列表:除第一个元素外的每个元素中的一个,除最后一个元素外的每个元素中的一个.然后,我们想要的平均值是从两个列表中得出的每对平均值.我们使用zip从两个列表中进行配对.

我假设即使输入值是整数,您也希望在结果中看到小数.默认情况下,Python会进行整数除法:它会丢弃余数.为了完全划分事物,我们需要使用浮点数.幸运的是,将一个整数除以浮点数将产生一个浮点数,因此我们只将2.0用作除数,而不是2.

因此:

averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]

问题2:

使用sum应该可以正常工作.以下作品:

a = range(10)
# [0,1,2,3,4,5,6,7,8,9]
b = sum(a)
print b
# Prints 45

此外,您不需要在此过程的每个步骤中都将所有内容分配给变量. print sum(a)正常工作.

您将必须更加确切地写出您所写的内容以及它是如何工作的.

I have a list of numbers such as [1,2,3,4,5...], and I want to calculate (1+2)/2 and for the second, (2+3)/2 and the third, (3+4)/2, and so on. How can I do that?

I would like to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on.

Also, how can I sum a list of numbers?

a = [1, 2, 3, 4, 5, ...]

Is it:

b = sum(a)
print b

to get one number?

This doesn't work for me.

解决方案

Question 1: So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, ... etc.

We make two lists: one of every element except the first, and one of every element except the last. Then the averages we want are the averages of each pair taken from the two lists. We use zip to take pairs from two lists.

I assume you want to see decimals in the result, even though your input values are integers. By default, Python does integer division: it discards the remainder. To divide things through all the way, we need to use floating-point numbers. Fortunately, dividing an int by a float will produce a float, so we just use 2.0 for our divisor instead of 2.

Thus:

averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]

Question 2:

That use of sum should work fine. The following works:

a = range(10)
# [0,1,2,3,4,5,6,7,8,9]
b = sum(a)
print b
# Prints 45

Also, you don't need to assign everything to a variable at every step along the way. print sum(a) works just fine.

You will have to be more specific about exactly what you wrote and how it isn't working.

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

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