我需要将“分数”从高到低排列在“名称”旁边,但不会让我,它会在列表中按顺序打印“分数”和“名称”
(“获胜者”的名字和“积分”的整数)
import csv
score=points
username=winner
with open ("write.csv", "a", newline='') as file:
fields=['score', 'name']
writer=csv.DictWriter(file, fieldnames=fields)
writer.writerow({'score' : score, 'name' : username})
with open ("write.csv", "r") as file:
sortlist=[]
reader=csv.reader(file)
for i in reader:
sortlist.append(i)
for i in range(len(sortlist)): #it does not order correctly
if i != 0:
time.sleep(0.1)
print()
print("The End")
time.sleep(1)
print()
print("LeaderBoards")
print()
time.sleep(1)
for i in range(len(sortlist)1):
print(sortlist[i])
我希望输出与名称(即
)从最高到最低['53', 'James']
['26', 'Bob']
['65', 'John']
To-
['65', 'John']
['53', 'James']
['26', 'Bob']
All i need is a line or a couple for it to print highest to lowest alongside the 'username'
答案 0 :(得分:0)
使用pandas更容易,就像这样....(在确保已安装pandas之前.... pip安装pandas)
import pandas as pd
df=pd.read_csv('write.csv',delimiter=',')
#With pandas
print(df.sort(['score'], ascending=[0]))
#To list
list = df.values.tolist()
print(list)
答案 1 :(得分:0)
在您的情况下,您希望使用两个列表而不是字典进行比较。
在答案中,我添加了建设性的注释,解释了做什么。我没有包括重复的分数清理,而是评论了提示,因为我怀疑这是家庭作业。但是,您对我的代码有一种解决过去的感觉(发布时这不是您的问题的一部分)。那里的印刷品显示发生了什么。享受。
# an extra data entry included to show duplicate issue you might encounter with your dataset.
list_1 = [['53', 'James'], ['65', 'James'], ['26', 'Bob'], ['65', 'John']]
list_temp = []
values_seen = []
values_dup = [] # add here your score duplicates (see comment below)
ids = 0 # positional ID tag for each data-entry if score is similar to one in list (gets
# filtered out if you make it a dict but remains in lists). This allows you to id
# duplicates in names and scores but are in fact two different persons.
for item in list_1: # add unique position identifier (in case there are similar names in the list with different score.)
ids +=1
list_temp.append((item[0], ids))
values_seen.append(item[0]) # hook to check later for duplicate scores.
l = list(reversed(sorted(list_temp))) # sorted score from highest to lowest
print (list_temp)
print (l)
list_final = []
# link name to its score.
for item in l:
print (item[1])
list_final.append([item[0], list_1[item[1]-1][1]])
print (list_final, '\n', values_seen)
print ("...and the winner is : %s" % list_final[0]) # procedure does not take into account shared winners.
另一种选择是:
with open ("write.csv", "r") as file:
sortlist=[]
reader=csv.reader(file)
for i in reader:
sortlist.append(i)
sortlist.sort(reverse=True)
...snippet...
更新:
在with open ("write.csv", "r") as file:
和for i in range(len(sortlist)):
之间可以执行我上面建议的排序。
with open ("write.csv", "r") as file:
sortlist=[]
reader=csv.reader(file)
for i in reader:
sortlist.append(i)
# a variation of l = list(reversed(sorted(list_temp))) using "sortlist" goes here
# sorted score from highest to lowest. Keep in mind duplicate scores.
for i in range(len(sortlist)): #it does not order correctly
if i != 0:
time.sleep(0.1)
答案 2 :(得分:0)
我所需要的只是 sortlist.sort(reverse = True)