给定一个数字列表,例如:

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

我如何计算它们的总和:

1 + 2 + 3 + 4 + 5 + ...

我如何计算他们的两两平均值:

[(1+2)/2, (2+3)/2, (3+4)/2, (4+5)/2, ...]

当前回答

在Python 3.8中,可以使用新的赋值操作符

>>> my_list = [1, 2, 3, 4, 5]
>>> itr = iter(my_list)
>>> a = next(itr)
>>> [(a + (a:=x))/2 for x in itr]
[1.5, 2.5, 3.5, 4.5]

A是对列表中前一个值的运行引用,因此它被初始化为列表的第一个元素,迭代发生在列表的其余部分,在每次迭代中使用后更新A。

显式迭代器用于避免使用my_list[1:]创建列表的副本。

其他回答

一种简单的方法是使用iter_tools排列

# If you are given a list

numList = [1,2,3,4,5,6,7]

# and you are asked to find the number of three sums that add to a particular number

target = 10
# How you could come up with the answer?

from itertools import permutations

good_permutations = []

for p in permutations(numList, 3):
    if sum(p) == target:
        good_permutations.append(p)

print(good_permutations)

结果是:

[(1, 2, 7), (1, 3, 6), (1, 4, 5), (1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 1, 7), (2, 3, 
5), (2, 5, 3), (2, 7, 1), (3, 1, 6), (3, 2, 5), (3, 5, 2), (3, 6, 1), (4, 1, 5), (4, 
5, 1), (5, 1, 4), (5, 2, 3), (5, 3, 2), (5, 4, 1), (6, 1, 3), (6, 3, 1), (7, 1, 2), 
(7, 2, 1)]

注意,顺序很重要——即1,2,7也表示为2,1,7和7,1,2。您可以通过使用集合来减少这种情况。

问题1:

要对一组数字求和,使用sum:

xs = [1, 2, 3, 4, 5]
print(sum(xs))

这个输出:

15

问题2:

所以你需要(元素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:])]

我使用一个while循环来得到结果:

i = 0
while i < len(a)-1:
   result = (a[i]+a[i+1])/2
   print result
   i +=1

你可以试试这种方法:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sm = sum(a[0:len(a)]) # Sum of 'a' from 0 index to 9 index. sum(a) == sum(a[0:len(a)]
print(sm) # Python 3
print sm  # Python 2

简短而简单:

def ave(x,y):
  return (x + y) / 2.0

map(ave, a[:-1], a[1:])

这是它的样子:

>>> a = range(10)
>>> map(ave, a[:-1], a[1:])
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]

由于Python在处理两个列表上的映射时有些愚蠢,你必须截断列表a[:-1]。如果你使用itertools.imap,它会像你期望的那样工作:

>>> import itertools
>>> itertools.imap(ave, a, a[1:])
<itertools.imap object at 0x1005c3990>
>>> list(_)
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]