【问题标题】:How to store numeric input in a loop如何在循环中存储数字输入
【发布时间】:2022-01-13 20:45:39
【问题描述】:

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

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: ')))

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

这是我正在尝试制作的程序: enter image description here

【问题讨论】:

    标签: python list for-loop multiple-input


    【解决方案1】:

    如果你想要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]]
    

    【讨论】:

    • 先生,您的代码几乎接近我的要求。但它可以重复吗?当我输入 1 个姓名和 3 个分数时,循环结束。但是如果我再次输入之前的值仍然存在。
    • 我发布了运行代码的结果作为我的答案的一部分——您可以看到它要求三个名称和三组每组三个分数,并在最后打印它们。这不是你想要的吗?
    • @Gaga 无法将分数存储在 python 文件中。
    【解决方案2】:

    您的意思是每次运行脚本时,它都会再次请求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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 2020-02-21
      相关资源
      最近更新 更多