while i<10:
a = a + i
print (a)
i = i+1
或者
for i in range(10):
sum = sum + i
print
0
1
3
6
10
15
21
28
36
45
那么如何通过编写更多代码将它们加在一起呢?我的意思是 1+3+6+10+15+21+... 然后将总数设置为变量!如果你能在两个循环中都给我看,那就太好了:)
这个怎么样:
total, totaltotal = 0, 0
for i in range(10):
total += i
totaltotal += total
print total, totaltotal
或者,您可以列出总计并存储它们以单独操作:
total, totals = 0, []
for i in range(10):
total += i
totals.append(total)
print total
totaltotal = 0
for i in range(10):
totaltotal += totals[i]
print totaltotal
您可能希望将其重写为列表推导式(甚至是生成器表达式),作为一个有用的练习。
In [26]: summ=0
In [27]: foo=0
In [28]: for i in range(10):
sum+=i #add i to summ
foo+=sum #add summ to foo
....:
....:
In [31]: sum
Out[31]: 45
In [32]: foo
Out[32]: 165
或单线:
In [58]: sum(map(sum,map(range,range(1,11))))
Out[58]: 165
timeit
比较:
In [56]: %timeit sum(sum(i + 1 for i in range(n)) for n in range(1000))
10 loops, best of 3: 128 ms per loop
In [57]: %timeit sum(map(sum,map(range,range(1,1001))))
10 loops, best of 3: 27.4 ms per loop
怎么样
sum(sum(i + 1 for i in range(n)) for n in range(10))
(如果你想要一个pythonic方法)