这个问题在这里已有答案:
我正在python中创建一个程序,它将随机数写入列表,并相互添加。当然,我能做到
x = list[0] + list[1] + list[2] + ... + list[100]
但我不想写这一切。 :)
不需要循环
sum(your_list[:101])
您可以执行以下操作:
x = 0
for i in range(100):
x+=list[i]
total = 0
for element in l:
total = total+element
print total
l
是你的列表变量。
你可以试试:
total=sum(list)
print(total)
如果这是你的整个清单,
x = sum(list)
如果你真的想跳过第一个元素list
[0]`以及索引101之外的任何东西,
x = sum(list[1:101])
顺便说一句,不要调用你的变量list
(你将隐藏内置数据类型)。
以下是解决此典型问题的一些可用选项:
import random
# generate random numbers
N = 100
lst = [random.random() for i in range(N)]
# method1 - for loop
total = 0
for v in lst:
total += v
# method2 - sum
total = sum(lst)
# method3 - generate & and acumulate in a single loop
total = 0
for v in range(N):
total += random.random()
# method4 - generate & sum in a single loop
total = sum([random.random() for i in range(N)])
只挑一个:)