按字母,平均,从最高到最低

时间:2016-03-09 18:02:13

标签: python sorting

再回来关于我的项目的另一个问题。所以我试图在我的文本文件中按降序排序我的分数。但是,它输出语法错误。 当用户输入class_name时,会在上面创建文件名,因此文件名等于filename。但是,它会输出错误。

这是我的一些代码:

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.")

1 个答案:

答案 0 :(得分:1)

第一次打开,尝试:

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)])