在我的课程作业中,我一直在尝试对分数文件进行数字排序并将其打印到python中
我曾尝试在代码中实现stackoverflow的其他答案,但没有成功。你知道吗
这是我的代码:
if sortmethod == ("n"):
with open(filename) as f:
f = {}
scores=[]
for name, v in f.items():
scores.append((name, score))
for name, score in sorted(scores, key=lambda a: a[1], reverse=True):
print(name, scores)
谢谢你的帮助。你知道吗
完整代码(如果需要):
import random
import operator
OPERATIONS = [
(operator.add, "+"),
(operator.mul, "*"),
(operator.sub, "-")
]
NB_QUESTIONS = 10
def get_int_input(prompt=''):
while True:
try:
return int(input(prompt))
except ValueError:
print("Not a valid input (integer is expected)")
def get_bool_input(prompt=''):
while True:
val = input(prompt).lower()
if val == 'yes':
return True
elif val == 'no':
return False
else:
print("Not a valid input (yes/no is expected)")
if __name__ == '__main__':
name = input("What is your name?").title()
class_name = input("Which class do you wish to input results for? ")
print(name, ", Welcome to the OCR Controlled Assessment Maths Test")
score = 0
for _ in range(NB_QUESTIONS):
num1 = random.randint(1,25)
num2 = random.randint(1,25)
op, symbol = random.choice(OPERATIONS)
print("What is", num1, symbol, num2)
if get_int_input() == op(num1, num2):
print("Correct")
score += 1
else:
print("Incorrect")
print("Well done", name, "you scored", score, "/", NB_QUESTIONS)
filename = class_name + ".txt"
with open(filename, 'a') as f:
f.write(str(name) + str(score) + '\n')
sortmethod = input("How do you wish to sort the scores. A = Alphabetically N = Numerically").lower()
if sortmethod == ("a"):
with open(filename, 'a') as f:
f = open(filename, "r")
lines = [line for line in f if line.strip()]
f.close()
lines.sort()
if sortmethod == ("n"):
with open(filename) as f:
f = {}
scores=[]
for name, v in f.items():
scores.append((name, score))
for name, score in sorted(scores, key=lambda a: a[1], reverse=True):
print(name, scores)
打开文件并将对它的引用放入
f
,然后将f
更改为指向空字典。(以下各行)—所以分数总是空的,你永远不会得到任何印刷品。你知道吗
我认为您应该将双变量的名称更改为其他名称,然后在打开文件后,您应该读取它并将值放入字典中。我们不知道您的文件是如何构造的,因此我们无法在这方面帮助您。你知道吗
还有,你在其他地方做类似的事情,你应该避免做这样的事情-
另外,另一个建议是,当您在以下行中写入文件时-
你没有在你的名字和分数之间加任何分隔符,你应该在那里加上某种分隔符,这样当你回读时,你就可以很容易地辨认出名字和分数。要使用的标准分隔符是
comma - ','
。你知道吗相关问题 更多 >
编程相关推荐