python数字求和程序,对Python中的数字列表求和

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值