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

时间:2015-05-07 22:03:28

标签: 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)

1 个答案:

答案 0 :(得分:2)

首先,您的代码不会执行您在标题中所说的内容。只需要很少的修改,它就会:new_output,output和results变量混合起来。

以下代码附加到output变量:

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

但稍后,您将重复new_output,这是一个空列表。

for item in new_output:
    new_output.append(float(item))

在这种情况下,第二次循环的原因是未知的,所以让我们暂时跳过它。关于输出的求和 - len(new_output)将始终为0,因为len本身返回可迭代中元素的数量,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))

此代码还假设结束位置是所有new_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从中选择其中一个结果,忽略概率。

相关问题