gpt4 book ai didi

python - 游戏排名系统 : Finding the people who beat the people: How do I organize this csv data and append the file?

转载 作者:行者123 更新时间:2023-11-28 16:58:29 25 4
gpt4 key购买 nike

我正在创建一个棋盘游戏排名系统,并且我有一个 .CSV 列表,列出了在棋盘游戏之夜打败其他人的人。打败一个打败了另一个人的人算作胜利。我需要抓取这个 CSV 文件,找到被获胜者击败的人击败的人,然后附加该数据并对其进行排序。

我可以打开、创建、抓取数据并写入文件,但是当我尝试编写各种版本的代码时,我似乎无法完全正确地获得输出。

 import csv
import collections

#get the contents of the input.csv file
WINLOSE = {}
with open('input.csv') as f2:
for line in f2:
winners,losers = line.strip().split(',')
WINLOSE[winners] = losers

new_items = set()
RESULTS = collections.namedtuple('RESULTS', ['winners', 'losers'])

#Write to the output file.
with open('output.csv', 'w') as f1:
writer = csv.DictWriter(winners, losers)

#pseudo code -- if any name in the winner cell appears in the
#loser cell,
#copy all of the losers associated with that cell to the people
#who beat that
#cell

if cell.losers = any-cell.winners:
append the losers associated with the winners cell
for row in new_items:
writer.writerow(row._asdict())

输入的 csv 如下所示:

 Winners,Losers
John,Amanda
Mark,Eddy
Amanda,Chad
Becky,Michael
Michael,Steve
Eddy,Fred
Michael, Stuart
Edwardo, Patricia
Michael, Buzz
Mark, Charlie
Amanda, Brandon
Brandon, Dirk

输出的 csv 应该是这样的:

 Winners,Losers
John,Amanda
John,Chad
John, Brandon
John, Dirk
Mark,Eddy
Mark,Fred
Mark, Charlie
Amanda,Chad
Becky,Michael
Becky,Steve
Michael,Steve
Michael, Stuart
Michael, Buzz
Eddy,Fred
Edwardo, Patricia
Amanda, Brandon
Brandon, Dirk

例如,John 打败了 Amanda,Amanda 打败了 Chad,因此我们需要添加一条 John 打败 Chad 的条目。

最佳答案

您可以构建一个将每个赢家映射到输家列表的字典,遍历字典的键/赢家,使用生成器函数递归地产生赢家的输家并输出结果赢家/输家对:

import csv

def find_losers(winner, results):
for loser in results.get(winner, ()):
yield loser
for child in find_losers(loser, results):
yield child

with open('output.csv', 'w') as f1, open('input.csv') as f2:
reader = csv.reader(f2)
writer = csv.writer(f1)
writer.writerow(next(reader))
results = {}
for winner, loser in reader:
results.setdefault(winner, []).append(loser)
for winner in results:
for loser in find_losers(winner, results):
writer.writerow((winner, loser))

使用您的示例输入,输出文件将包含:

Winners,Losers
John,Amanda
John,Chad
John,Brandon
John,Dirk
Mark,Eddy
Mark,Fred
Mark,Charlie
Amanda,Chad
Amanda,Brandon
Amanda,Dirk
Becky,Michael
Becky,Steve
Becky,Stuart
Becky,Buzz
Michael,Steve
Michael,Stuart
Michael,Buzz
Eddy,Fred
Edwardo,Patricia
Brandon,Dirk

关于python - 游戏排名系统 : Finding the people who beat the people: How do I organize this csv data and append the file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56028317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com