我目前正在使用 globals()[eval()] 轻松迭代数据库,但是当我将其放入函数并尝试使用 locals() 时,它无法正确访问变量。
for fighter in ['1', '2']:
win = 0
loss = 0
for outcome in ['win', 'loss']:
tko = 0
sub = 0
dec = 0
for method in ['tko', 'sub', 'dec']:
for rnd in ['1', '2', '3', '4', '5', '6']:
globals()[eval('outcome')] += fights_fighters_table[
'r' + rnd + '_' + method + '_' + outcome + '_' + fighter]
globals()[eval('method')] += fights_fighters_table[
'r' + rnd + '_' + method + '_' + outcome + '_' + fighter]
# ADD TKO/SUB/DEC WINS/LOSSES TO DATAFRAME
fights_fighters_table[method + '_' + outcome + '_' + fighter] = globals()[eval('method')]
globals()[eval('outcome')] += fights_fighters_table['dq_' + outcome + '_' + fighter]
fights_fighters_table[outcome + '_' + fighter] = globals()[eval('outcome')]
我想从一系列其他文件将参数传递给这个代码块,所以我相信我需要将它包装在一个函数中,但是我无法让全局变量在函数中工作,并且 locals() 也不会访问直接 for 循环之外的变量。
我尝试将所有 globals() 调用更改为 locals(),希望它能够访问函数内的任何变量,但 eval() 返回一个空系列。
编辑: Fights_fighters_table 行示例:
r1_tko_win_1 = 4
r2_tko_win_1 = 2
r3_tko_win_1 = 0
r1_tko_loss_1 = 1
r2_tko_loss_1 = 0
r3_tko_loss_1 = 2
r1_sub_win_1 = 0
r2_sub_win_1 = 1
r2_sub_win_1 = 0
r1_sub_loss_1 = 1
r2_sub_loss_1 = 1
r3_sub_loss_1 = 0
我希望将这些内容独立地添加到每一行中,从而产生一个具有如下结果的数据框:
win_1 = 7
loss_1 = 5
tko_win_1 = 6
sub_win_1 = 1
tko_loss_1 = 3
sub_loss_1 = 2
每排有两名战斗机需要进行此操作。
表格截图:(我不知道更好的方式来显示它) fights_fighters_table 的截图部分
我相信如果你使用字典来保存你的求和,你可以摆脱所有
global()
和eval()
的东西。
看看这是否能让你再次朝着可以工作的方向前进。
## --------------------------
## Rows of tuples from a database
## --------------------------
fights_fighters_table = [
("r1_tko_win_1", 4),
("r2_tko_win_1", 2),
("r3_tko_win_1", 0),
("r1_tko_loss_1", 1),
("r2_tko_loss_1", 0),
("r3_tko_loss_1", 2),
("r1_sub_win_1", 0),
("r2_sub_win_1", 1),
("r2_sub_win_1", 0),
("r1_sub_loss_1", 1),
("r2_sub_loss_1", 1),
("r3_sub_loss_1", 0)
]
## --------------------------
## --------------------------
## total up the various values for the components of the key
## this works because every component of the key is distinct.
## --------------------------
totals = {}
for key, value in fights_fighters_table:
fight_round, method, outcome, fighter = key.split("_")
new_key = f"{outcome}_{fighter}"
totals[new_key] = totals.get(new_key, 0) + value
new_key = f"{method}_{outcome}_{fighter}"
totals[new_key] = totals.get(new_key, 0) + value
## --------------------------
import json
print("Summary:")
print(json.dumps(totals, indent=4))
这应该给你:
Summary:
{
"win_1": 7,
"tko_win_1": 6,
"loss_1": 5,
"tko_loss_1": 3,
"sub_win_1": 1,
"sub_loss_1": 2
}
最终,如果这确实对您有帮助,它可能会作为以下重复项被关闭: