gpt4 book ai didi

python - 打印字典错误: list indices must be integers or slices,不是元组

转载 作者:行者123 更新时间:2023-12-01 07:55:08 24 4
gpt4 key购买 nike

我有这样的字典:

team_dict = {
'Iran': {
'wins':ir_win,
'loses':ir_lose,
'draws':ir_draws,
'goal difference':ir_goal,
'points':ir_score
},
'Spain': {
'wins':sp_win,
'loses':sp_lose,
'draws':sp_draws,
'goal difference':sp_goal,
'points':sp_score
},
'Portugal': {
'wins':po_win,
'loses':po_lose,
'draws':po_draws,
'goal difference':po_goal,
'points':po_score
},
'Morocco': {
'wins':ma_win,
'loses':ma_lose,
'draws':ma_draws,
'goal difference':ma_goal,
'points':ma_score
}
}

然后我对它进行了排序:

sorted_team_dict = sorted(
team_dict.items(),
key = lambda x: (-x[1].get('points'), -x[1].get('wins'), x[1].get('keys')
)
)

我想打印排序后的结果:

for item in sorted_team_dict:
print(
"%s wins:%i , loses:%i , draws:%i , goal difference:%i , points:%i" % (
sorted_team_dict[item]["keys"],
sorted_team_dict[item]["wins"],
sorted_team_dict[item]["loses"],
sorted_team_dict[item]["draws"],
sorted_team_dict[item]["goal difference"],
sorted_team_dict[item]["points"]
)
)

但是我遇到了以下错误:

list indices must be integers or slices, not tuple

我无法理解错误的含义。

最佳答案

这里的问题是 sorted_team_dict 不是字典,而是元组列表。所以你可以像这样迭代它:

for key, value in sorted_team_dict:
print("%s wins:%i , loses:%i , draws:%i , goal difference:%i , points:%i" %(key,value["wins"],value["loses"],value["draws"],value["goal difference"],value["points"]))

您可能应该将其重命名为 sorted_team_items 或其他名称。该代码也可以使用其他清理,但这超出了本问题的范围。

关于python - 打印字典错误: list indices must be integers or slices,不是元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56025985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com