-1

我想制作两个列表,第一个包含三个名称,第二个包含三个分数列表:

name_list = [[name1][name2][name3]] 
score_list = [[22,33,35][32,22,34][32,44,50]]

我目前的代码是这样的:

name = []
name.append(input('input students name: '))
    
score = []
for i in range(3):
    score.append(int(input('input students scores: ')))

我想保存三个名称和三个分数列表,但它只保存最后输入的名称和值。

这是我正在尝试制作的程序: 在此处输入图像描述

4

2 回答 2

2

如果你想要 3 个名字和 3 组分数,你需要另一个for循环:

names = []
scores = []
for _ in range(3):
    names.append(input('input students name: '))
    scores.append([])
    for _ in range(3):
        scores[-1].append(int(input('input students score: ')))

print(f"names: {names}")
print(f"scores: {scores}")
input students name: name1
input students score: 22
input students score: 33
input students score: 35
input students name: name2
input students score: 32
input students score: 22
input students score: 34
input students name: name3
input students score: 32
input students score: 44
input students score: 50
names: ['name1', 'name2', 'name3']
scores: [[22, 33, 35], [32, 22, 34], [32, 44, 50]]
于 2021-12-08T23:10:57.297 回答
0

您的意思是每次运行脚本时,它都会score再次要求该值?即,它不会在会话之间保存?

如果是这样,您可以将每个var的值保存在存储在脚本文件夹中的文本文件中。

您可以解决的一种方法是:

def get_vars():
  try:
    fil = open("var-storage.txt", "r") # open file
    fil_content = str(fil.read()) # get the content and save as var
    # you could add some string splitting right here to get the
    # individual vars from the text file, rather than the entire
    # file
    fil.close() # close file
    return fil_content
  except:
    return "There was an error and the variable read couldn't be completed."


def store_vars(var1, var2):
  try:
        with open('var-storage.txt', 'w') as f:
          f.write(f"{var1}, {var2}")
        return True
  except:
        return "There was an error and the variable write couldn't be completed."

# ofc, you would run write THEN read, but you get the idea
于 2021-12-08T23:15:02.353 回答