需要将列表[1]中的所有数字添加到列表[100] [重复]

问题描述 投票:-3回答:6

这个问题在这里已有答案:

我正在python中创建一个程序,它将随机数写入列表,并相互添加。当然,我能做到

x = list[0] + list[1] + list[2] + ... + list[100]

但我不想写这一切。 :)

python python-3.x
6个回答
1
投票

不需要循环

sum(your_list[:101])

0
投票

您可以执行以下操作:

   x = 0
   for i in range(100):
       x+=list[i]

0
投票
total = 0
for element in l:
    total = total+element
print total

l是你的列表变量。


0
投票

你可以试试:

total=sum(list)
print(total)

0
投票

如果这是你的整个清单,

x = sum(list)

如果你真的想跳过第一个元素list [0]`以及索引101之外的任何东西,

x = sum(list[1:101])

顺便说一句,不要调用你的变量list(你将隐藏内置数据类型)。


0
投票

以下是解决此典型问题的一些可用选项:

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)])

只挑一个:)

© www.soinside.com 2019 - 2024. All rights reserved.