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']}
与使用两个单独的列表相比,这可能是保存数据的一种更简洁的方式。