按字母,平均,从高到低的顺序对分数和名称进行排序 [英] Sorting scores and names alphabetical, average, highest to lowest
本文介绍了按字母,平均,从高到低的顺序对分数和名称进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
再次返回有关我的项目的另一个问题.因此,我尝试在文本文件中按降序对分数进行排序.但是,它输出语法错误. 当用户输入class_name时,在上面创建了文件名,因此等于文件名.但是,它会输出错误.
Back again with another question about my project. So I've tried to sort my scores in descending order in my text file. However, it outputs a syntax error. The filename is created above when the user inputs the class_name and so thats what equals filename. However, it outputs an error.
这是我的一些代码:
filename = class_name + ".txt"
with open(filename, 'a+') as w:
w.write(str(name) + " : " + str(score) + '\n')
print("Your results are being updated ...")
time.sleep(2)
print("Your score has been updated")
print("")
w.close()
if get_bool_input("Do you wish to view the previous results from your class: "): #The 'get_bool_input' will determine if they input yes or no and will either open the file or not.
selection= input("Do you wish to view the results in Alphabetical order(A), scores highest to lowest(B) or average score highest to lowest?(C)")
if selection == 'A':
with open(filename, 'r') as r:
for name in sorted(r):
print(name, end='')
if selection == 'B':
with open(filename, 'r') as r:
file_sorted = sorted((ast.literal_eval(x) for x in r),key=lambda z:(int(z[1]),z[0]),reverse=True)
r.close()
if selection not in ['A','B','C']:
print ("Error, type in A, B or C.")
如何使其返回"selection ="问题?如果未选择A,B或C.
How to make it loop back to the 'selection=' question? If A,B or C are not selected.
if get_bool_input("Do you wish to view the previous results from your class: "): #The 'get_bool_input' will determine if they input yes or no and will either open the file or not.
selection= input("Do you wish to view the results in Alphabetical order(A), scores highest to lowest(B) or average score highest to lowest?(C)")
if selection == 'A':
print (alphabetically(data))
if selection == 'B':
print (by_score(data))
if selection == 'C':
print (by_average(data))
if selection not in ['A','B','C']:
print ("Error, type in A, B or C.")
else:
input ("Press any key to exit")
编辑
像这样吗?
while True:
if selection == 'A':
print (alphabetically(data))
elif selection == 'B':
print (by_score(data))
elif selection == 'C':
print (by_average(data))
return True
else: selection not in ['A','B','C']:
print ("Error, type in A, B or C.")
推荐答案
第一次打开,尝试:
with open(filename, 'a+') as write_file:
....
然后第二次打开:
with open(filename, 'r+') as read_file:
...
也许会起作用
编辑
现在首先考虑您的文件解析和排序方法,我想到了这一点:
Now regarding first your file parsing and the sorting methods, I came up with this:
from collections import defaultdict
from collections import OrderedDict
filename = 'file.txt'
def alphabetically(some_data):
return OrderedDict(
(k, some_data[k]['scores'])
for k in sorted(some_data)
)
def by_score(some_data, descending=True):
return OrderedDict(
(k, sum(some_data[k]['scores']))
for k in sorted(some_data,
key=lambda k: sum(some_data[k]['scores']),
reverse=descending)
)
def by_average(some_data, descending=True):
def average(scores):
return float(sum(scores)) / len(scores)
return OrderedDict(
(k, average(some_data[k]['scores']))
for k in sorted(some_data,
key=lambda k: average(some_data[k]['scores']),
reverse=descending)
)
data = defaultdict(dict)
with open(filename, 'r+') as f:
for line in f.read().splitlines():
name, score = line.split(' : ')
scores = data[name].get('scores', [])
scores.append(int(score))
data[name]['scores'] = scores
print alphabetically(data)
print by_score(data)
print by_average(data)
输出:
OrderedDict([('ADAM', [2]), ('Da', [3, 0, 1]), ('Dadsid', [4]), ('Davd', [3, 4]), ('Dliid', [9]), ('Dloed', [1]), ('Dsid', [3]), ('lukedd', [8]), ('mathe', [4, 12])])
OrderedDict([('mathe', 16), ('Dliid', 9), ('lukedd', 8), ('Davd', 7), ('Da', 4), ('Dadsid', 4), ('Dsid', 3), ('ADAM', 2), ('Dloed', 1)])
OrderedDict([('Dliid', 9.0), ('lukedd', 8.0), ('mathe', 8.0), ('Dadsid', 4.0), ('Davd', 3.5), ('Dsid', 3.0), ('ADAM', 2.0), ('Da', 1.3333333333333333), ('Dloed', 1.0)])
这篇关于按字母,平均,从高到低的顺序对分数和名称进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文