python - 使用函数从列表创建字典
问题描述
我正在研究一个超级联赛数据集,我需要创建一个字典,其中键是球队,值是他们的相对点。我有一个团队列表和一个函数,该函数从比赛中获取结果并将其转换为团队的积分。我得到了一切好,但问题是,它不是为所有团队及其分数创建一个字典,而是为每个团队打印 20 个字典。怎么了?
解决方案
您正在每次迭代中创建一个新字典。相反,您应该在循环之前制作字典,然后在每次迭代时添加一个新条目:
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 这样的名字真的很糟糕,因为:
- 它们不是描述性的
- 他们隐藏来自打字模块的内置类(你应该使用)
- 他们违反了 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,它会在您运行时突出显示错误。而且您的代码也变得更加清晰,可供其他开发人员(包括未来的您)理解和使用。
推荐阅读
- azure - 在 Synapse Analytics 上优化 Azure 分析服务处理
- powershell - 无法将 SharePoint (PnP) 连接传递到 PowerShell 作业,因为它正在反序列化?
- angular - Angular:如果没有输入,则不显示 HTML 属性
- java - Jsoup Login in to website仅返回html的头部
- mysql - 在不使用子查询的情况下为 CREATE VIEW 重新构造查询?
- sql - 用“-”分隔列(用于 xml 路径)
- powershell - 使用 PowerShell 解析 Win32 可执行输出
- pandas - 在df python中动态创建列
- python - autoAugment 函数的返回
- python - 参数化 kusto 函数的异常输入