我正在为世界杯创建一个模拟器,并尝试为此进行预选赛,我给了每个团队一个“team_value”,我想将其乘以一个随机数,然后我希望有一个列表,其中的团队按顺序排序按降序排列,第一队得分最高。在下面的代码中只有几支球队,但想象一下有多个预选组
import random
team_list = [
{"team": "France", "team_value": "2.2", "gs_scores": 0},
{"team": "England", "team_value": "1.6", "gs_scores": 0},
{"team": "Italy", "team_value": "1.6", "gs_scores": 0},
{"team": "Argentina", "team_value": "2.2", "gs_scores": 0},
{"team": "Brazil", "team_value": "2.0", "gs_scores": 0},
]
for team in team_list:
multiplier = random.randint(0,25)
gs_scores = gs_scores+multiplier*team_value
print (gs_scores)
x = sorted(team, reverse=True)
print(x)
这里有很多东西要解压:
team_list
和您的 for
循环缩进不一致,因此您的代码将无法运行。
team_value
中每个字典的team_list
属性不应该是字符串。
在
for
循环内,您没有访问相关 team
的属性。例如,使用字典键语法team["team_value"]
来访问字典的值并在相关计算中使用它们。
要根据
gs_scores
属性的值对列表进行排序(假设这就是您想要做的?),您需要一个函数,该函数将返回 gs_scores
属性以作为排序后的 key
kwarg 传递功能:
import random
def get_gs_scores(team):
return team["gs_scores"]
team_list = [
{"team": "France", "team_value": 2.2, "gs_scores": 0},
{"team": "England", "team_value": 1.6, "gs_scores": 0},
{"team": "Italy", "team_value": 1.6, "gs_scores": 0},
{"team": "Argentina", "team_value": 2.2, "gs_scores": 0},
{"team": "Brazil", "team_value": 2.0, "gs_scores": 0},
]
for team in team_list:
multiplier = random.randint(0,25)
team["gs_scores"] = team["gs_scores"]+multiplier*team["team_value"]
print (gs_scores)
x = team_list.sort(key=get_gs_scores, reverse=True)
print(x)