在 python 中生成结果总和

generate sum of results in python

我们有一个游戏,游戏有 500 个回合。在每一轮中,同时掷出两个硬币,如果两个硬币都有 'heads' 那么我们赢 1 英镑,如果两个硬币都有 'tails' 那么我们输 1 英镑,如果有一个情况硬币显示 'heads' 而另一个硬币显示 'tails' 反之亦然,那么我们只是 'try again'.

coin_one = [random.randint(0, 1) for x in range(500)]
coin_two = [random.randint(0, 1) for x in range(500)]

game = zip(coin_one, coin_two)

for a, b in game:
    if a and b:
        print(1)
    elif not a and not b:
        print(-1)
else:
    print('please try again') # or continue

结果是:

1 请再试一遍 -1 请再试一遍 请再试一遍 请再试一遍 -1 -1 1个 -1 ,......, 1

我试图找到结果的总和,以便我可以知道游戏玩家在游戏完成后(500 回合)赢了多少或输了多少。

在获得只玩一场游戏(500轮)的结果(总量won/lost)后,我希望玩游戏100次以创建一些汇总统计数据,如均值、最大值、最小值和标准差玩这个游戏。

您可以简单地将值的总和累加到一个新变量中:

total = 0
for a, b in game:
    if a and b:
        total += 1
    elif not a and not b:
        total -= 1
    else:
        print('please try again')

print(total)

如果你不想打印任何东西,因为它们都有不匹配的值,你可以做一个one-liner:

s = sum(0 if a^b else (-1, 1)[a and b] for a, b in game)

请注意,^ 是异或运算符,如果两个操作数相同,则 returns 为 falsy 值。把它放在三元中,我们可以 select -1 或 1 通过用 and 两个操作数的快捷方式索引结果。

正如其他人所建议的,total 就是您要搜索的内容。在循环之前定义它,然后它在循环中得到in/decremented。

total = 0
for a, b in game:
    if a and b:
        total += 1
    elif not a and not b:
        total -= 1