循环并将结果添加到每次迭代的列表中

2024-04-24 21:32:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个程序,输出1000个数字,然后打印它们的总和。在

我怎样才能循环它100次,每次都把总和加到一个新的列表中?在

import random

output=[] 
new_output=[]
outcome =[]


choices = [('0.1', -1), ('0.3', 0), ('0.3', 3), ('0.3', 4)]
prob = [cnt for val, cnt in choices]
for i in range (1000):  
    output.append(random.choice(prob))
    for item in new_output:
        new_output.append(float(item))

amount = len(new_output)
print(new_output)

print('The end positon is', amount)

Tags: in程序newforoutput数字randomitem
1条回答
网友
1楼 · 发布于 2024-04-24 21:32:44

首先,你的代码并不像你在标题中所说的那样。只要稍加修改,它就会:新的输出、输出和结果变量就有点混在一起了。在

以下代码附加到output变量:

for i in range (1000):  
     output.append(random.choice(prob))

但是稍后,您将迭代new_output,这是一个空列表。在

^{pr2}$

在本例中,第二个循环的原因是未知的,现在让我们跳过它。关于输出的求和-len(new_output)将始终为0,因为len本身返回iterable中的元素数,new_output是一个空列表。如果需要循环输出的长度,则必须引用正确的变量:

amount = len(output)

但这并不是输出的总和—为此,有一个方便的函数sum来完成您需要的操作。在

amount = sum(new_output)

固定代码可能如下所示:

import random

output = []
new_output = []
outcome = []


choices = [('0.1', -1), ('0.3', 0), ('0.3', 3), ('0.3', 4)]
prob = [cnt for val, cnt in choices]
for i in range(1000):
    new_output.append(random.choice(prob))

amount = sum(new_output)

print new_output
print('The end positon is', amount)

现在,变量没有混合在一起,你正在总结输出。要执行此操作100次,请将此功能放入另一个循环中,该循环将运行100次:

import random

output = []
new_output = []
outcome = []


choices = [('0.1', -1), ('0.3', 0), ('0.3', 3), ('0.3', 4)]
prob = [cnt for val, cnt in choices]
for j in range(100):
    for i in range(1000):
        new_output.append(random.choice(prob))

    amount = sum(new_output)
    output.append(amount)

print output
print('The end positon is', sum(output))

此代码还假定结束位置是所有新输出的总和(随机数之和)。一个额外的提示:如果您不关心范围内的值,请使用_-(for _ in range(100))。这将大大减少命名空间污染。在

可能还有一个关于概率的问题-

choices = [('0.1', -1), ('0.3', 0), ('0.3', 3), ('0.3', 4)]
prob = [cnt for val, cnt in choices]

构造一个列表

[-1, 0, 3, 4]

random.choice从中选取一个结果,忽略了概率。在

相关问题 更多 >