gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:25:15 27 4
gpt4 key购买 nike

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

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

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.

Class6A.txt用python打开:{'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]}

最佳答案

  1. 使用sorted()方法按字母排序列表。
  2. 计算平均分并根据平均分创建学生名单

演示:

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

if-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 expettype casting 期间捕获 Value Error 异常。

演示:

>>> 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 使用输入

关于python - 如何使用 python 将保存在 .txt 文件中的分数和名称按字母顺序排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29747443/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com