在python中,我希望得到范围(5)中所有x的x / 2之和,而不使用追加到list和sum。我该怎么办?
答案 0 :(得分:0)
# if you're on Python 2 you need the next line:
from __future__ import division
count = 0
for x in range(5):
count += x / 2
print count
count
现在将包含值5.0
,我相信这是你所追求的。
答案 1 :(得分:0)
如果您有一个任意列表,您可以手动循环遍历这些项并添加值:
someList = range(5)
total = 0
for x in someList:
total += x / 2.0
print(total)
当您将每个项目除以2时,您还可以先将原始项目值相加,然后在结束时除以一次:
someList = range(5)
total = 0
for x in someList:
total += x
total = total / 2.0
print(total)
当然,如果您知道要将所有数字从1加到N(在您的情况下为4),您也可以使用simple maths to solve this:
n = 4
total = (n * (n + 1)) / 2.0 # sum of numbers 1 to N
total = total / 2.0 # result divided by two as per your requirements
# or in one line
total = (n * (n + 1)) / 4.0