如果条件不起作用,但其他条件有效



当我在python控制台中运行以下代码时,它可以按预期工作。然而,当我在oree中运行它时,只考虑else条件。因此,即使条件得到满足,我也只能得到3.85和0.1(而不是2或1.6(的结果

for k in range(1,11):
locals()['choice' + str(k)] = random.randint(0,1)
locals()['resultHL' + str(k)] = []
win = []
for i in range(1, 11):
choice = 0
exec(f'choice+=choice{i}')
rnum = random.random()
probability = i / 10
if rnum <= probability:
win.append(1)
if choice == 1:
exec(f'resultHL{i} = 2')
else:
exec(f'resultHL{i} = 3.85')
else:
win.append(0)
if choice == 1:
exec(f'resultHL{i} = 1.6')
else:
exec(f'resultHL{i} = 0.1')

由于oTree中的语法,我必须以特定的方式生成变量。

class Player(BasePlayer):
number_entered = models.FloatField(min=0, max=100)
result_risk = models.FloatField()
win_risk = models.BooleanField()
for k in range(1,11):
locals()['choice' + str(k)] = make_booleanfield()
locals()['probHL' + str(k)] = models.FloatField()
locals()['winHL' + str (k)] = models.BooleanField()
locals()['resultHL' + str(k)] = models.FloatField()
del k
def make_booleanfield():
return models.BooleanField(
choices=[[True,'A'],[False,'B'],],
widget=widgets.RadioSelectHorizontal,
)

class ResultsHL(Page):
@staticmethod
def vars_for_template(player: Player):
for i in range(1, 11):
choice = 0
exec(f'choice+=player.choice{i}')
rnum = random.random()
probability = i / 10
exec(f'player.probHL{i}=probability')
if rnum <= probability:
exec(f'player.winHL{i}=1')
if choice == 1:
exec(f'player.resultHL{i} = C.A_win')
else:
exec(f'player.resultHL{i} = C.B_win')
else:
exec(f'player.winHL{i}=0')
if choice == 1:
exec(f'player.resultHL{i} = C.A_lose')
else:
exec(f'player.resultHL{i} = C.B_lose')

locals()/exec()的东西可能有一个作用域错误——与其试着调试它,我建议只使用dicts或list。下面是一个使用三个列表而不是20个int和一个列表的示例,其中有一个存根Player类来模拟您的用例:

import random
class Player:
def __init__(self):
self.result = 0.0

choices = [random.randint(0, 1) for _ in range(10)]
players = [Player() for _ in range(10)]
wins = [int(random.random() <= i / 10) for i in range(1, 11)]
for player, choice, win in zip(players, choices, wins):
if win:
if choice:
player.result = 2
else:
player.result = 3.85
else:
if choice:
player.result = 1.6
else:
player.result = 0.1

print([player.result for player in players])

打印(例如(:

[1.6, 0.1, 1.6, 0.1, 1.6, 0.1, 2, 3.85, 0.1, 2]

我可能还建议使用一个表来减少if/else的内容:

results = (
(2.00, 3.85),  # win
(1.60, 0.10),  # loss
)
for player, choice, win in zip(players, choices, wins):
player.result = results[win][choice]

最新更新