如何使用python将保存在.text文件中的分数和名称按字母顺序排序?

时间:2015-04-20 12:06:31

标签: python sorting

import pickle
def startover():
    #Tells the user what number corresponds with what class.
    print('1 = classA, 2 = classB, 3 = classC')

    #accepts an input for what class the user would like to view.      
    Class=int(input('Choose the class you would like to view.'))

    #If class a is selected, open class a.
    if Class == int('1'):
        ClassA=open('Class6A.txt','rb')
        clsa=pickle.load(ClassA)
        print(clsa)


        #If class b is selected, open class b.
    if Class == int('2'):
        ClassB=open('Class6B.txt','rb')
        clsb=pickle.load(ClassB)
        print(clsb)


        #If class c is selected, open class c.
    if Class == int('3'):
        ClassC=open('Class6C.txt','rb')
        sorttype=int(input('How do you want to sort this data? 1=alphabetical 2=High to low by highest number 3=High to low by average number.'))
        clsc=pickle.load(ClassC)
        print(clsc)


    file=('Class6A.txt','rb')
startover()

我希望能够按用户按字母顺序对选定的代码进行排序,以便他们可以使用代码输出的分数轻松找到名称。

Inside Class6a.txt

:€}q (X    WHITE SAMq]q(KK  KeX   WILLIAMS GABRIELLEq]q(K
KKeX
   NATHAN WILSONq]q(KK  KeX   SMITH ISABELLEq]q(KK  KeX
   CLARK BRANDONq   ]q
(KKKeX   PATEL SAPNAq]q(KKKeX
   BROWN ADAMq
]q(KK
KeX   JONES CHLOEq]q(KKKeX
   DAVIS RYANq]q(K
KK  eX   MILLER NOELq]q(KKKeu.

在python中打开Class6A.txt: {' WILLIAMS GABRIELLE':[10,6,2],' JONES CHLOE':[7,5,5],' MILLER NOEL':[1, 8,6],' CLARK BRANDON':[8,6,1],' NATHAN WILSON':[7,9,6],' SMITH ISABELLE' :[2,9,6],' WHITE SAM':[1,9,5],' BROWN ADAM':[8,10,6],' PATEL SAPNA':[7,8,7],' DAVIS RYAN':[10,6,9]}

2 个答案:

答案 0 :(得分:3)

  1. 使用 sorted()方法按字母排序列表。
  2. 根据平均分数进行计算以找到标记的平均值并创建学生列表
  3. 演示:

    import pickle
    
    d = {'WILLIAMS GABRIELLE': [10, 6, 2], 'JONES CHLOE': [7, 5, 5],\
         'MILLER NOEL': [1, 8, 6], 'CLARK BRANDON': [8, 6, 1],\
         'NATHAN WILSON': [7, 9, 6], 'SMITH ISABELLE': [2, 9, 6],\
         'WHITE SAM': [1, 9, 5], 'BROWN ADAM': [8, 10, 6], 'PATEL SAPNA': [7, 8, 7],\
         'DAVIS RYAN': [10, 6, 9]}
    
    with open("Class6A.txt", "wb") as fp:
        pickle.dump(d, fp)
    
    import pickle
    import collections
    
    def getAverage(data):
        """ Create Average of student data """
        records = dict()
        for i, j in data.iteritems():
            records[i] = (j, float(sum(j))/len(j))
    
        return records
    
    def startover():
        #. Tells the user what number corresponds with what class.
        print('1 = classA, 2 = classB, 3 = classC')
        #. accepts an input for what class the user would like to view.      
        while 1:
            try:
                class_no = int(raw_input('Choose the class you would like to view.'))
                if class_no not in [1,2,3]:
                    print "Enter vlaid Class Number."
                    continue
                break
            except ValueError:
                print "Enter valid Class Numner i.e.digit"
                continue
    
        #. If class a is selected, open class a.
        if class_no==1:
            file_name = 'Class6A.txt'
            #If class b is selected, open class b.
        elif class_no==2:
            file_name = 'Class6B.txt'
            #If class c is selected, open class c.
        elif class_no==3:
            file_name = 'Class6C.txt'
    
        while 1:
            try:
                sorttype = int(raw_input('How do you want to sort this data? 1=alphabetical\
                 2=High to low by highest number 3=High to low by average number.'))
                if sorttype not in [1,2,3]:
                    print "Enter vlaid option from the list.."
                    continue
                break
            except ValueError:
                print "Enter valid option Number i.e. digit"
                continue
    
    #    fp = open(file_name, 'rb')
    #    data = pickle.load(fp)
    #    fp.close()
    
        with open(file_name, "rb") as fp:
            data = pickle.load(fp)
    
        #- Add Average value in data.
        records = getAverage(data)
    
        if sorttype==1:
            student_names = records.keys()
            student_names = sorted(student_names)
        elif sorttype==3:
            student_names = []
            tmp = collections.defaultdict(list)
            for i, j in records.iteritems():
                tmp[j[1]].append(i)
            tmp1 = tmp.keys()
            tmp1 = sorted(tmp1)
            tmp1.reverse()
            for i in tmp1:
                student_names.extend(tmp[i])
        elif sorttype==2:
            student_names = []
            print "Try your self."
    
        print "Result:"
        print "Name\t Marks\t Average"
        for i in student_names:
            print "%s\t%s\t%s"%(i, records[i][0], records[i][1])
    
    
    startover()
    

    <强>输出:

    1 = classA, 2 = classB, 3 = classC
    Choose the class you would like to view.1
    How do you want to sort this data? 1=alphabetical             2=High to low by highest number 3=High to low by average number.1
    Result:
    Name     Marks   Average
    BROWN ADAM  [8, 10, 6]  8.0
    CLARK BRANDON   [8, 6, 1]   5.0
    DAVIS RYAN  [10, 6, 9]  8.33333333333
    JONES CHLOE [7, 5, 5]   5.66666666667
    MILLER NOEL [1, 8, 6]   5.0
    NATHAN WILSON   [7, 9, 6]   7.33333333333
    PATEL SAPNA [7, 8, 7]   7.33333333333
    SMITH ISABELLE  [2, 9, 6]   5.66666666667
    WHITE SAM   [1, 9, 5]   5.0
    WILLIAMS GABRIELLE  [10, 6, 2]  6.0
    
    --------------------
    1 = classA, 2 = classB, 3 = classC
    Choose the class you would like to view.1
    How do you want to sort this data? 1=alphabetical             2=High to low by highest number 3=High to low by average number.3
    Result:
    Name     Marks   Average
    DAVIS RYAN  [10, 6, 9]  8.33333333333
    BROWN ADAM  [8, 10, 6]  8.0
    PATEL SAPNA [7, 8, 7]   7.33333333333
    NATHAN WILSON   [7, 9, 6]   7.33333333333
    WILLIAMS GABRIELLE  [10, 6, 2]  6.0
    SMITH ISABELLE  [2, 9, 6]   5.66666666667
    JONES CHLOE [7, 5, 5]   5.66666666667
    WHITE SAM   [1, 9, 5]   5.0
    MILLER NOEL [1, 8, 6]   5.0
    CLARK BRANDON   [8, 6, 1]   5.0
    

    如果-elif的-ELSE

    当我们想要在同一个变量上检查多个条件时使用if elif else。

    <强>演示

    >>> a = 51
    >>> if a<0:
    ...   print "Number is negative."
    ... elif a==0:
    ...   print "Number is Zero."
    ... else:
    ...   print "Number is greater than 0"
    ... 
    Number is greater than 0
    

    异常处理

    try expet期间使用Value Error来捕获type casting例外情况。

    演示:

    >>> a = raw_input("Enter option:")
    Enter option:f
    >>> a
    'f'
    >>> int(a)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: 'f'
    >>> try:
    ...   int(a)
    ... except ValueError:
    ...   print "Enter digit only.."
    ... 
    Enter digit only..
    

    注意:

    对Python 2.x使用raw_input

    使用Python 3.x的输入

答案 1 :(得分:1)

您的pickle文件中包含dict。您想要阅读dict.items()和内置sorted()函数的文档 - 这应该足以解决您的问题。

注意:我不会给你准确的(而且很简单)代码,因为它确实看起来像是家庭作业。