[英]adding tuples to a list in an if loop (python)
我正在 python 中使用 symbulate 进行概率课程并运行一些模拟。
设置:A 和 B 两支球队正在参加“n 局最佳”系列赛,其中 n 是奇数。 在这个例子中,n=7,A 队赢得任何一场比赛的概率是 0.55。 假设 A 队赢得第一场比赛,估计他们赢得系列赛的概率。
这是我到目前为止所得到的,我认为这是正确的:
model = BoxModel([1, 0], probs=[0.55, .45], size=7, replace=True)
test = model.sim(10000)
for x in range(0,10000):
test1 = test[x]
if test1[0] == 1:
print (test1)
test1
最后两行是我遇到困难的地方。 这种'for' 和'if' 组合使得只显示以'1' 开头的输入(即A 队赢得第一场比赛)。 我需要将这些输入保存到一个表中,以便我可以对其进行一些进一步的测试。
当这些循环正在运行时,如何将 test1 的值输入到表中? 目前,test1 只输出 x=10,000 的值。
编辑:“测试”产生一个列表,0-10000,所有可能的游戏结果。 我需要一个仅包含以“1”开头的游戏结果的列表。
Edit2:“test”的输出(在我运行“for”或“if”之前)看起来像:
Index Result
0 (1, 1, 1, 0, 0, 1, 1)
1 (0, 1, 0, 1, 1, 0, 0)
2 (1, 1, 1, 1, 0, 1, 0)
3 (0, 0, 1, 1, 1, 1, 1)
4 (0, 0, 0, 0, 0, 0, 0)
5 (1, 1, 0, 1, 0, 0, 1)
6 (0, 0, 1, 0, 1, 1, 1)
7 (0, 1, 0, 0, 0, 0, 1)
8 (1, 1, 0, 1, 0, 1, 0)
... ...
9999 (1, 1, 0, 1, 0, 0, 0)
我需要一个“测试”(或另一个变量)来包含看起来完全一样的东西,但只包含以“1”开头的行。
所以您要存储每个测试的结果? 为什么不将它们存储在list
?
test1_results = []
for x in range(0,10000):
test1 = test[x]
# check if first element in sequence of game outcomes is a win for team A
if test1[0] == 1: # or '1' if you're expecting string
test1_results.append(test1)
您可以运行print(test1_results)
来打印整个结果列表,但如果要打印前n
结果,请执行print(test1_results[:n])
。
如果你想要你的if
语句在那里,你将不得不稍微调整位置。 你的test
对象是什么样的? 你能给我们一个小样本吗?
编辑:更新if
语句以反映下面的评论
根据您的评论:
results_that_start_with_one = []
for result in test:
result_string = str(result)
if result_string[0] == "1":
results_that_start_with_one.append(result_string)
这将遍历列表“测试”中的每个结果。 它将每个转换为一个字符串(我假设它们是一些数值)。 然后它取字符串中的第一个字符,并询问它是否为 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.