![](/img/trans.png)
[英]Python - Sorting a list of strings (names and scores) from highest to lowest
[英]Sorting scores and names alphabetical, average, highest to lowest
再次返回有关我的项目的另一个问题。 因此,我尝试在文本文件中按降序对分数进行排序。 但是,它输出语法错误。 当用户输入class_name时,在上面创建了文件名,因此等于文件名。 但是,它输出一个错误。
这是我的一些代码:
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。
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:
...
也许会起作用
编辑
现在首先考虑您的文件解析和排序方法,我想到了:
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)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.