在 Python 中求和一个数字列表

2022-01-09 00:00:00 python list sum

问题描述

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

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?

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

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, ...]

是吗:

b = sum(a)
print b

得到一个号码?

这对我不起作用.


解决方案

问题 1:所以你想要 (element 0 + element 1)/2, (element 1 + element 2)/2, ... 等等

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

p>

我们制作了两个列表:一个除了第一个之外的每个元素,一个除了最后一个之外的每个元素.那么我们想要的平均值是从两个列表中获取的每一对的平均值.我们使用 zip 从两个列表中获取对.

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.

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

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.

因此:

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

问题 2:

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

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

此外,您无需在沿途的每一步都将所有内容分配给变量.print sum(a) 工作得很好.

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.

相关文章