给定一个数字列表,例如:
[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, ...]
当前回答
使用简单的列表-理解和求和:
>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5
其他回答
我使用一个while循环来得到结果:
i = 0
while i < len(a)-1:
result = (a[i]+a[i+1])/2
print result
i +=1
我只使用带有map()的
a = [1,2,3,4,5,6,7,8,9,10]
b = map(lambda x, y: (x+y)/2.0, fib[:-1], fib[1:])
print b
让我们让初学者容易:-
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
你可以试试这种方法:
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
对一串数字求和:
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:]))