你如何在python中创建排行榜?

时间:2016-09-28 09:46:30

标签: python

我正在为我的学校开展一个项目,我想知道是否有办法在python中建立排行榜?我是python的新手,到目前为止,我所做的是获取用户的输入并将其存储在文本文件中。我不确定如何继续。感谢任何帮助,谢谢!

x = 0

Name = [None]*1000
Class = [None]*1000
Score = [0]*100

# opens the text file called text_file
text_file = open("write.txt","a")

# puts in the values of the highest scores and "saves it" by closing and opening the file
def write_in_file():
    global text_file
    text_file.write(Name[x])
    text_file.write("\n")
    text_file.write(Class[x])
    text_file.write("\n")
    text_file.write(Score[x])
    text_file.write("\n")
    text_file.write("\n")
    text_file.close()
    text_file = open("write.txt","a")

# asks for player data and puts highest value in a file
for i in Name:
    Name[x] = input("Name:")
    Class[x] = input("Class:")
    Score[x] = input("Score:")
    write_in_file()
    print(Score)
    x += 1

2 个答案:

答案 0 :(得分:1)

您可以使用pandas制作排行榜榜单。这是一个示例:

import pandas as pd

df = pd.DataFrame({'Name': ['x','y','z'],
                   'Class':  ['B','A','C'],
                    'Score' : [75,92,56]})
print (df)

Out[3]: 
  Class Name  Score
0     B    x     75
1     A    y     92
2     C    z     56


# changing order of columns
df = df.reindex_axis(['Name','Class','Score'], axis=1)

# appending
df.loc[3] = ['a','A', 96]

print (df)

Out[15]: 
  Name Class  Score
1    y     A     92
3    a     A     96
0    x     B     75
2    z     C     56

# sorting
df = df.sort(['Class', 'Score'], ascending=[1, 0])

print (df)

Out[16]: 
  Name Class  Score
3    a     A     96
1    y     A     92
0    x     B     75
2    z     C     56

答案 1 :(得分:0)

这是一个可能有帮助的代码

import csv

score=input("whats ya score")
username=input("whats ya name")

with open ("protleader.csv", "a", newline='') as file:
    fields=['score', 'name']
    writer=csv.DictWriter(file, fieldnames=fields)
    writer.writerow({'score' : score, 'name' : username})

with open ("protleader.csv", "r") as file:
    sortlist=[]
    reader=csv.reader(file)
    for i in reader:
        sortlist.append(i)
for i in range(len(sortlist)):
    if i != 0:
        sortlist[i][0]=int(sortlist[i][int(0)])


print("")

print("Unsorted:")
for i in range(len(sortlist)):
    print(sortlist[i])


for i in range(555):
    for i in range(len(sortlist)-1):
        if i != 0:
            if sortlist[i][0] < sortlist[i+1][0]:
                change=sortlist[i]
                sortlist[i]=sortlist[i+1]
                sortlist[i+1]=change


print("")

print("Sorted and cut:")
for i in range(len(sortlist)-1):
    print(sortlist[i])