需要帮助编写和读取文件以及将数据存储到列表中

时间:2017-10-31 04:09:28

标签: python list if-statement while-loop floating-point

我需要加权等级计算器的帮助,我有计算数据和加权平均值所需的比特。我的问题是导入数据并存储它。我想我需要使用列表但我不知道如何分隔每个条目,我知道我可以使用.split(),我可能会这样做。但我真正的问题是弄清楚如何存储这些值,然后写入输出文件。

这就是.txt文件对我输入到我的程序的输入看起来像是"打开了(" scores.txt"," r&#34 ;)"命令

Babbage, Charles
10.0   9.5    8.0  10.0
 9.5  10.0    9.0
85.0  92.0   81.0
Turing, Alan
10.0   8.0    6.0
10.0  10.0    9.0   9.5
90.0  92.0   88.5
Hopper, Grace
10.0  10.0    8.0
10.0  10.0    9.0   9.5
90.0  92.0   88.0
Van Rossum, Guido
 7.5   8.5
 7.5   8.5    6.0   9.0
68.0  81.0   70.0
Backus, John
 9.5   9.5   10.0   8.0   9.5  10.0
 7.5   8.5    6.0   9.0  10.0
99.0  93.0  100.0
Crawley, Bryan
 6.0
 7.5
70.0  60.0   55.5

我尝试过使用s.isdigit和s.isalpha并没有真正起作用。第一行是测验,第二行是项目,第三行是考试。测验和考试的数量是任意的,考试总是有三个。

这是输出需要的样子:

Babbage, Charles      89.4   B
Turing, Alan          91.3   A
Hopper, Grace         92.7   A
Van Rossum, Guido     75.5   C
Backus, John          94.4   A
Crawley, Bryan        63.9   D

以下是我的代码现在的样子:

quiz_scores = []

while True:
    score = float(input("Quiz #{} ----- ".format(len(quiz_scores)+1)))
    if score == -1:
        break
    quiz_scores.append(score)
quiz_total = sum(quiz_scores) - min(quiz_scores)
if len(quiz_scores)>1:
    quiz_avg =  (quiz_total/((len(quiz_scores))-1)*10)
else:
    quiz_avg = (quiz_total/(len(quiz_scores)*10)

print()

project_scores = []

while True:
    score2 = float(input("Project #{} -- ".format(len(project_scores)+1)))
    if score2 == -1:
        break
    project_scores.append(score2)

project_total = sum(project_scores)
project_avg = (project_total/(len(project_scores))*10)

print()

exam1 = float(input("Exam #1 ----- "))
exam2 = float(input("Exam #2 ----- "))


print()

final = float(input("Final Exam -- "))

average = ((quiz_avg*.15)+(project_avg*.20)+(exam1*.20)+(exam2*.20)+(final*.25))

print("Average ---- %.2f" % average)



if 90 <= average <= 100:
    print("Grade ------- A")
if 80 <= average < 90:
    print("Grade ------- B")
if 70 <= average < 80:
    print("Grade ------- C")
if 60 <= average < 70:
    print("Grade ------- D")
if 0 <= average < 60:
    print("Grade ------- F")

绝对希望在这里学习,而不仅仅是复制和粘贴您评论的内容;如果我有一些问题,请耐心等待。

谢谢你们,这个社区非常有帮助。

3 个答案:

答案 0 :(得分:0)

你可能想要使用.csv。通过导入csv或pandas,可以将数据保存到csv文件或从csv文件加载数据。

有关详细信息,请参阅官方文档。

答案 1 :(得分:0)

编辑:我删除了NumPy和Pandas的用法。如果您想要更详细或具体的问题答案,您应该更新原始问题或加入评论。

如果您无法在制作之前选择数据输入的样子,例如@martineau建议,您可以执行以下操作:

# Ordered dictionary will let us add keys to a dictionary {}, but if we
# access the keys, it will retain the order we added them, which is not
# the default behaviour of a normal dict.
from collections import OrderedDict

# Load the file and sequentially add lines for users. You can simplify
# if they always have 3 lines each
with open('scores.txt') as f:

    out_dict = OrderedDict()
    # Load in each line from the file
    for line in f.readlines():

        # remove commas, replace(), strip newline characters '\n', strip();
        # split the line on spaces '81 81 30' -> ['81', '81', '30']
        line_split = [i for i in line.strip().replace(',', '').split(' ') if i != '']

        # From your current format, we know that some lines start with a character when there is a name, or a digit if it is a number
        # float('4') will give 4
        # float('s') will raise a ValueError exception
        #

        try:
            # If we do not raise an exception, we know it is an integer/float
            vals = [float(i) for i in line_split]
            # We can keep adding the values to the last entry in our dictionary, i.e., to the last name we created
            # As we used OrderedDict, we do not have to worry that we will retrieve a random key.
            out_dict[[i for i in out_dict.keys()][-1]].extend(vals)
        except ValueError:
            # So, if we raise an exception, we know it is 'Charles Babbage'
            # A new name is a new key, so put a new key in out_dict, and make the value a list we can keep adding to
            out_dict[line.strip()] = []

然后你可以随心所欲地使用这本词典。您也可以让get_scoreget_grade按照您的意愿工作,因为我现在只是取平均值,因为我没有完全理解您的意图....

# Some functions to define how the score and grading works
def get_score(scores):
    return sum(scores)/(1.0*len(scores))

def get_grade(score):
    if 90 <= score <= 100:
        return 'A'
    if 80 <= score < 90:
        return 'B'
    if 70 <= score < 80:
        return 'C'
    if 60 <= score < 70:
        return 'D'
    if 0 <= score < 60:
        return 'E'

for key, item in out_dict.items():
    print(key, get_score(item), get_grade(get_score(item)))

输出如下:

Babbage, Charles 32.4 E
Turing, Alan 33.3 E
Hopper, Grace 33.65 E
Van Rossum, Guido 29.5555555556 E
Backus, John 27.8214285714 E
Crawley, Bryan 39.8 E

答案 2 :(得分:0)

希望你能理解这里所做的事情..如果您有任何问题,请告诉我。

gradebook={}
input_name = input("Enter input file:")
output_name = input("Enter input file:")

with open(input_name,"r") as file:
    for line in file:
        if line[0].isalpha():
            gradebook[line.strip()] = {'quizzes':next(file).strip().split(' '), 
                                        'projects':next(file).strip().split(' '), 
                                        'tests':next(file).strip().split(' ')
                                        }
for student, values in gradebook.items():
    quizzes = []
    projects = []
    tests = []
    for category, grades in values.items():
        for grade in grades:
            if grade != '':
                exec("%s.append(float(grade))"% category)
                # ^^^ THIS IS THE SAME AS THE FOLLOWING 
                #if category == 'quizzes':
                #   quizzes.append(float(grade))
                #if category == 'projects':
                #   projects.append(float(grade))
                #if category == 'tests':
                #   tests.append(float(grade))

    quiz_total = sum(quizzes) - min(quizzes)

    if len(quizzes)>1:
        quiz_avg =  (quiz_total/((len(quizzes))-1)*10) 
    else:
        quiz_avg = (quiz_total*10) #no reason to divide by len(quizzes) if it is 1

    project_total = sum(projects)
    project_avg = (project_total/(len(projects))*10)

    exam1 = tests[0]
    exam2 = tests[1]
    final = tests[2]

    average = ((quiz_avg*.15)+(project_avg*.20)+(exam1*.20)+(exam2*.20)+(final*.25))

    if 90 <= average <= 100:
        final_grade = "A"
    if 80 <= average < 90:
        final_grade = "B"
    if 70 <= average < 80:
        final_grade = "C"
    if 60 <= average < 70:
        final_grade = "D"
    if 0 <= average < 60:
        final_grade = "F"

    with open(output_name,"a") as file:
        file.write("{0:20} {1:0.1f} {2:>4}\n".format(student, average, final_grade))

这输出以下内容:

Babbage, Charles     89.4    B
Turing, Alan         91.3    A
Hopper, Grace        92.7    A
Van Rossum, Guido    75.5    C
Backus, John         94.3    A
Crawley, Bryan       54.9    F

不确定为什么布莱恩克劳利的成绩低于你的预期?