给定一个数字列表,例如:
[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, ...]
当前回答
>>> a = range(10)
>>> sum(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del sum
>>> sum(a)
45
sum似乎已经在代码的某个地方定义了,并且覆盖了默认函数。所以我删除了它,问题解决了。
其他回答
本着itertools的精神。灵感来自双人食谱。
from itertools import tee, izip
def average(iterable):
"s -> (s0,s1)/2.0, (s1,s2)/2.0, ..."
a, b = tee(iterable)
next(b, None)
return ((x+y)/2.0 for x, y in izip(a, b))
例子:
>>>list(average([1,2,3,4,5]))
[1.5, 2.5, 3.5, 4.5]
>>>list(average([1,20,31,45,56,0,0]))
[10.5, 25.5, 38.0, 50.5, 28.0, 0.0]
>>>list(average(average([1,2,3,4,5])))
[2.0, 3.0, 4.0]
我使用一个while循环来得到结果:
i = 0
while i < len(a)-1:
result = (a[i]+a[i+1])/2
print result
i +=1
n = int(input("Enter the length of array: "))
list1 = []
for i in range(n):
list1.append(int(input("Enter numbers: ")))
print("User inputs are", list1)
list2 = []
for j in range(0, n-1):
list2.append((list1[j]+list1[j+1])/2)
print("result = ", list2)
使用简单的列表-理解和求和:
>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5
问题2: 对一组整数求和:
a = [2, 3, 5, 8]
sum(a)
# 18
# or you can do:
sum(i for i in a)
# 18
如果列表中包含整数作为字符串:
a = ['5', '6']
# import Decimal: from decimal import Decimal
sum(Decimal(i) for i in a)