首页 > 解决方案 > 使用函数从列表创建字典

问题描述

我正在研究一个超级联赛数据集,我需要创建一个字典,其中键是球队,值是他们的相对点。我有一个团队列表和一个函数,该函数从比赛中获取结果并将其转换为团队的积分。我得到了一切好,但问题是,它不是为所有团队及其分数创建一个字典,而是为每个团队打印 20 个字典。怎么了?

在此处输入图像描述

标签: pythonpandaslistdictionary

解决方案


您正在每次迭代中创建一个新字典。相反,您应该在循环之前制作字典,然后在每次迭代时添加一个新条目:

def get_team_points(df, teams):
    team_points = {}
    for team_name in teams:
        num_points = ... # as you have it but since you posted an image I'm not rewriting it
        team_points[team_name] = num_points
    return team_points

一个更简洁的解决方案是使用字典理解

def get_team_points(df, teams):
    team_points = {team: get_num_points(team, df) for team in teams}
    return team_points

whereget_num_points是您的num_points = ...行的函数,如果您将代码发布为文本,我会再次输入:)

另外 - 请开始使用更好的变量名;)如果你这样做,你的生活会有所改善。像 List 和 Dict 这样的名字真的很糟糕,因为:

  1. 它们不是描述性的
  2. 他们隐藏来自打字模块的内置类(你应该使用)
  3. 他们违反了 pep8 命名约定

说到打字模块,它在起作用:

def get_team_points(df: pd.DataFrame, teams: List[str]) -> Dict[str, int]:
    team_points = {team: get_num_points(team, df) for team in teams}
    return team_points

现在您可以使用 mypy 之类的工具在错误发生之前捕获它们。如果您使用 IDE 而不是 jupyter,它会在您运行时突出显示错误。而且您的代码也变得更加清晰,可供其他开发人员(包括未来的您)理解和使用。


推荐阅读