【发布时间】:2019-01-15 01:25:19
【问题描述】:
我主要是自己编程,所以没有人检查我的代码。我觉得我已经养成了一堆坏习惯。
我在此处粘贴的代码有效,但我想听听其他一些解决方案。
我创建了一个名为teams_shots 的字典。我遍历了一个 pandas 数据框,该数据框在一行中包含客队和主队的名称。我想跟踪出现在数据框中的每个团队的投篮情况。这就是为什么我检查home_team_name 或away_team_name 在字典中是否没有条目,如果有,我创建一个。
for index,match in df.iterrows():
if match['home_team_name'] not in teams_shots:
#we have to setup an entry in the dictionary
teams_shots[match['home_team_name']]=[]
teams_shots[match['home_team_name']].append(match['home_team_shots'])
home_shots_avg.append(None)
else:
home_shots_avg.append(np.mean(teams_shots[match['home_team_name']]))
teams_shots[match['home_team_name']].append(match['home_team_shots'])
if match['away_team_name'] not in teams_shots:
teams_shots[match['away_team_name']]=[]
teams_shots[match['away_team_name']].append(match['away_team_shots'])
away_shots_avg.append(None)
else:
away_shots_avg.append(np.mean(teams_shots[match['away_team_name']]))
teams_shots[match['away_team_name']].append(match['away_team_shots'])
正如您所见,几乎相同的代码被编写了两次,这并不是良好编程的标志。我曾考虑在 if 语句中使用 or 运算符,但可能已经创建了一个条目,我会截断它。任何想法如何更好地编写此代码。
【问题讨论】:
-
我投票结束这个问题,因为我觉得它更适合Code Review 网站。
-
您的输入数据框 df 是什么样的?您的预期输出是什么?
标签: pandas dictionary dataframe logical-operators code-duplication