给定一个数字列表,例如:
[1, 2, 3, 4, 5, ...]
我如何计算它们的总和:
1 + 2 + 3 + 4 + 5 + ...
我如何计算他们的两两平均值:
[(1+2)/2, (2+3)/2, (3+4)/2, (4+5)/2, ...]
给定一个数字列表,例如:
[1, 2, 3, 4, 5, ...]
我如何计算它们的总和:
1 + 2 + 3 + 4 + 5 + ...
我如何计算他们的两两平均值:
[(1+2)/2, (2+3)/2, (3+4)/2, (4+5)/2, ...]
当前回答
这么多解决方案,但我最喜欢的还是没有:
>>> import numpy as np
>>> arr = np.array([1,2,3,4,5])
numpy数组与列表没有太大区别(在这个用例中),除了你可以像对待数字一样对待数组:
>>> ( arr[:-1] + arr[1:] ) / 2.0
[ 1.5 2.5 3.5 4.5]
完成了!
解释
花式索引的意思是:[1:]包括从1到最后的所有元素(因此省略了元素0),而[:-1]是除了最后一个以外的所有元素:
>>> arr[:-1]
array([1, 2, 3, 4])
>>> arr[1:]
array([2, 3, 4, 5])
将这两个元素相加,就得到了一个包含元素(1+2)(2+3)等的数组。 请注意,我是除以2.0,而不是2,因为否则Python认为您只使用整数并产生四舍五入的整数结果。
使用numpy的优点
Numpy比围绕数字列表的循环要快得多。这取决于你的列表有多大,快几个数量级。此外,它的代码更少,至少对我来说,它更容易阅读。 我正在努力养成对所有数字组都使用numpy的习惯,这对于我本来必须编写的所有循环和循环中的循环是一个巨大的改进。
其他回答
一种简单的方法是使用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。您可以通过使用集合来减少这种情况。
生成器是一种简单的编写方法:
from __future__ import division
# ^- so that 3/2 is 1.5 not 1
def averages( lst ):
it = iter(lst) # Get a iterator over the list
first = next(it)
for item in it:
yield (first+item)/2
first = item
print list(averages(range(1,11)))
# [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
这个问题在这里得到了解答
a = [1,2,3,4]
sum(a)
sum(a)返回10
让我们让初学者容易:-
global关键字将允许在主函数中分配全局变量消息,而不产生新的局部变量
message = "这是一个全局变量!" def main (): 全球信息 message = "This is a local" 打印(消息) main () #输出“这是一个本地”-从函数调用 打印(消息) #输出“This is a local”——从外部作用域
这个概念叫做影子
在Python中对数字列表求和
Nums = [1,2,3,4,5] Var = 0 def金额(): 对于nums中的num: 全局变量 Var = Var + num 打印(var) 如果__name__ == '__main__': 金额()
输出= 15
对一串数字求和:
sum(list_of_nums)
使用列表推导式生成一个新列表,其中相邻元素在xs中求平均值:
[(x + y) / 2 for x, y in zip(xs, xs[1:])]
将所有相邻元素求和为一个值:
sum((x + y) / 2 for x, y in zip(xs, xs[1:]))