我过去遇到过这个问题,从未找到过解决方案。我检查了吨的谷歌链接,但仍然不知道。 我想要做的是使用字符串作为变量。我正在使用SQLalchemy,因此将直接使用我的项目中的示例:(在函数中查找变量'objective')
以下是一个例子:
def win_ratio_p_obj(objective):
#want to find the win/loss ratio for each obj_first, ie. 60% of times when team gets fblood you also win vs. 40% of time you lose
obj_totals = session.query(Match.win, func.count(Match.win)).filter(Match.**objective** == 't').group_by(Match.win).order_by(Match.win).all()
win_chance = obj_totals[1][1]/(obj_totals[0][1]+obj_totals[1][1])
return win_chance
objective = 'first_dragon'
x = win_ratio_p_obj(objective)
objective = 'first_blood'
y = win_ratio_p_obj(objective)
objective = 'first_turret'
z = win_ratio_p_obj(objective)
objective = 'first_inhib'
返回:
Traceback (most recent call last):
Python Shell, prompt 15, line 1
builtins.AttributeError: type object 'Match' has no attribute 'objective'
所以我想要做的是将每个目标用作变量名,以减少代码重复。我知道我可以很容易地复制粘贴功能几次,但这看起来很傻。 目前,上面的代码不会将目标变量值识别为变量而不是字符串。
任何答案都将非常受欢迎!