该脚本需要从 text/csv 文件读取输入,但是一旦我尝试实现该功能,一切都会中断。这是我的代码:from collections import defaultdict#from csv import readerdata = """Lions 3, Snakes 3Tarantulas 1, FC Awesome 0Lions 1, FC Awesome 1Tarantulas 3, Snakes 1Lions 4, Grouches 0"""# with open('sample_input.csv') as data:# csv = reader(data)# list_csv = [line.rstrip('\n') for line in data]data_list = data.splitlines()def splitter(row): left_team, right_team = row.split(',') return { 'left': left_team[:-2].strip(), 'left_score': int(left_team[-2:].strip()), 'right': right_team[:-2].strip(), 'right_score': int(right_team[-2:].strip()) }data_dicts = [splitter(row) for row in data_list]team_scores = defaultdict(int)for game in data_dicts: if game['left_score'] == game['right_score']: team_scores[game['left']] += 1 team_scores[game['right']] += 1 elif game ['left_score'] > game['right_score']: team_scores[game['left']] += 3 else: team_scores[game['right']] += 3 print(team_scores)teams_sorted = sorted(team_scores.items(), key=lambda team: team[1], reverse=True)# for line in teams_sorted:# print(line)此外,我需要的预期输出是:1. Tarantulas, 6 pts2. Lions, 5 pts3. FC Awesome, 1 pt3. Snakes, 1 pt4. Grouches, 0 pts我似乎无法弄清楚如何到达这一步。我用打印语句检查了我的大部分代码,看起来字典工作正常,但它没有打印最后一支球队和它的分数(Grouches,0 分)。我目前得到这个输出:('Tarantulas', 6)('Lions', 5)('Snakes', 1)('FC Awesome', 1)任何帮助将不胜感激!
3 回答
qq_笑_17
TA贡献1818条经验 获得超7个赞
添加 CSV 时的代码中断。CSV 阅读器split(',')为您完成。所以你的left_team = row[0]和right_team = row[1]
所以你的代码变成了类似的东西
def spliter(row):
left_team, right_team = row
return {
'left': left_team[:-2].strip(),
'left_score': int(left_team[-2:].strip()),
'right': right_team[:-2].strip(),
'right_score': int(right_team[-2:].strip())
}
with open('data.csv') as data_obj:
reader = csv.reader(data_obj)
data_dicts = [splitter(row) for row in reader]
如果你想手动,你可以去纯文本阅读split(',')。
with open('data.csv') as data_obj:
data_list = [line.rstrip('\n') for line in data_obj.readlines()]
添加回答
举报
0/150
提交
取消