Question 1: So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, ... etc.
(问题1:你想要(元素0 +元素1)/ 2,(元素1 +元素2)/ 2,......等)
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. (我们使用zip
来从两个列表中获取对。)
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. (默认情况下,Python执行整数除法:它会丢弃余数。)
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
. (幸运的是,将一个int除以float会产生一个浮点数,所以我们只使用2.0
作为除数而不是2
。)
Thus:
(从而:)
averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]
Question 2:
(问题2:)
That use of sum
should work fine.
(使用sum
应该可以正常工作。)
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. (print sum(a)
工作正常。)
You will have to be more specific about exactly what you wrote and how it isn't working.
(您必须更准确地了解您所写的内容以及它的工作方式。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…