【问题标题】:Create a list within a list based on user input根据用户输入在列表中创建列表
【发布时间】:2021-08-20 08:29:37
【问题描述】:

我正在制作一个家庭作业待办事项列表程序,方法是使用 for 循环将输入添加到空列表中。在我的代码中,第一个 for 循环询问他们之前输入的主题数量的分配数量。这被分配给hw_amount。另一个 for 循环随后迭代 [hw_amount] 次。这个 for 循环请求分配名称并将其添加到 hw_list。我希望程序做的是通过将当前的 hw_name 添加到相应的列表中来自动在我的hw_list 中创建一个空列表。例如,hw_list 中的第一个列表将是具有一个分配(对象)的 Biology。下一个列表将是具有两个分配(对象)的数学。有人可以帮助我如何编写代码吗?我只有分配到同一个列表中。

class_list = []
hw_list = []
hw_name = None

def hw_run():
    global class_list
    global hw_list
    global hw_name
    for i in range(len(class_list)):
        hw_amount = int(input("\nEnter amount of assignments for " + str(class_list[i]) + ": ")) 
        for h in range(hw_amount):
            hw_name = input("\nEnter assignment for " + str(class_list[i]) + ": ")
            hw_list.append(hw_name)
            print(hw_list)
subject_run()  
hw_run()

这是我的程序的示例运行

列表打印出来显示追加的动作

【问题讨论】:

    标签: python list for-loop input append


    【解决方案1】:

    hw_name 可以是一个列表变量。这样您就可以在该主题的每个作业中附加该主题并将该列表附加到hw_list

    class_list = ['Biology', 'Math']
    hw_list = []
    hw_name = []      # Change from none to empty list
    
    def hw_run():
        global class_list
        global hw_list
        global hw_name
        for i in range(len(class_list)):
            hw_amount = int(input("\nEnter amount of assignments for " + str(class_list[i]) + ": "))
            hw_name = []     # You'll have to clear this for each subject otherwise you have duplicate assignments
            for h in range(hw_amount):
                hw_name.append(input("\nEnter assignment for " + str(class_list[i]) + ": ")) # Append the user input to hw_name list
            hw_list.append(hw_name) # Move this append to hw_list outside the loop to assing hw_name list to hw_list. Could be done inside the loop but not worth the hassle
            print(hw_list)
    subject_run() 
    hw_run()
    

    这是输出:

    Enter amount of assignments for Biology: 1
    
    Enter assignment for Biology: test
    [['test']]
    
    Enter amount of assignments for Math: 2
    
    Enter assignment for Math: quiz
    
    Enter assignment for Math: worksheet
    [['test'], ['quiz', 'worksheet']]
    

    除非您特别需要列表,否则我会使用字典。键是班级的,值是家庭作业。

    def subject_run():
        subject_list = {}   # Create empty dictionary
        while True:
            subject = input('Enter a subject name: ')   # User input for subject
            if subject.lower() == 'exit':   # If user enter 'exit' then return
                return subject_list
            else:
                subject_list.update({subject:[]})   # Add the subject to the dictionary with an empty list as the value
    
    def hw_run(class_list): # class_list as an argument, this is our dictionary which is returned from subject_run()
        for k in class_list.keys(): # Loop through all keys (subjects) in the dictionary
            hw_amount = int(input(f"\nEnter amount of assignments for {k}: ")) # User input of number of assignments
            for h in range(hw_amount): # Loop in range of assignments
                class_list[k].append(input(f"\nEnter assignment for {k}: ")) # Append the value (list) for the subject
        return class_list # Return the dictionary
    
    print(hw_run(subject_run()))
    

    这个输出:

    {'Biology': ['test'], 'Math': ['quiz', 'worksheet']}
    

    与使用两个单独的列表相比,这可能是保存数据的一种更简洁的方式。

    【讨论】:

      【解决方案2】:

      您的第一个问题是您没有连接两个阵列。在 for 循环的分配结束时,您已完成该主题,因此您可以将完成的数组保存到主数组,将其分配给您的主题。

      这将我们带到您的第二个问题。数组不是保存数据对的理想方式,如果您想将作业分配给我建议您使用 python dictionary 的主题。你可以让它像这样存储数据:

      class_list = {
        'Biology': ['test'],
        'Math': ['quiz', 'worksheet']
      }
      

      如果您已经像这样创建了字典,您现在可以将数组分配给正确的类并重置它。

      for key in class_list.keys():
              hw_amount = int(input("\nEnter amount of assignments for " + key + ": ")) 
              for h in range(hw_amount):
                  hw_name = input("\nEnter assignment for " + key + ": ")
                  hw_list.append(hw_name)
                  print(hw_list)
              class_list[key] = hw_list
              hw_list = []
      

      【讨论】:

        猜你喜欢
        • 2021-12-13
        • 2022-01-20
        • 2020-04-29
        • 2021-03-18
        • 2014-01-22
        • 2014-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多