且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对Python中的数字列表求和

更新时间:2023-02-05 14:24:22

问题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.