作为我作业的一部分,我有两个文件。其中有一份参与者名单,他们前面有数字。另一个文件具有与第一个列表相关的完成编号列表,例如:
第二个文件将包含: 3 1 2
所以比赛的结果是
如何对与第二个列表的索引对应的第一个列表进行排序?我似乎无法获得正确的结果索引,并且我不知道如何将其与初始参与者列表联系起来。
with open("participants.txt") as f:
participants = []
for line in f:
participants.append(line.strip().split(". "))
for i in range(len(participants)):
try:
participants[i][0] = int(participants[i][0])
except:
continue
with open("participantresults.txt") as d:
participantresults = []
for line in d:
participantresults.append(line.strip("\n"))
for i in range(len(participantresults)):
osalejate_tulemused[i] = int(osalejate_tulemused[i])
resultindex = []
for n in osalejate_tulemused:
resultindex.append(participantresults.index(n)) #faulty
result = []
for n in range(len(tulemusindex)):
.....
with open("tulemus.txt", "w") as f:
#write the list here later.
将您的参与者转换为字典,以便键是第一个文件中的他们的标识符。然后你可以通过第二个文件指向这些:
with open("participants.txt") as f:
participants = []
for i, line in enumerate(f):
participants.append(line.strip().split(". "))
participants = {index: name for index, name in participants}
with open("participantresults.txt") as d:
order = []
for line in d:
order.extend(line.strip().split(" "))
with open("tulemus.txt", "w") as fw:
for i, p_index in enumerate(order):
fw.write(f"{i+1}. {participants[p_index]}\n")