从内部列表中减去

Subtracting from inner list

有5个募捐项目,这个程序的目的是从每个项目的期望金额中减去n个捐助者每人捐出的金额

该程序部分运行,但有时 python 键入“TypeError:'NoneType' 对象不可订阅”并且程序失败

什么会导致此崩溃?

感谢您的帮助!


    
    
n_month = 5
nl = [[], [],[], [], []]

place = 1
var = 1

#creating list of lists of the format [sum, number of project].
# for example this one: [[53, 1], [78, 2], [152, 3], [51, 4], [39, 5]]

for lst in nl: 
    summ = int(input("Please input miminum budget for next project:")) 
    lst.append(summ)
    lst.insert(place, var)
    place +=2
    var+=1
    
n = int(input("Please enter number of donors: "))

for i in range(n):
    
    project_n = int(input("Please enter project number (1-5): "))
    donation = int(input("Please enter donation: "))
    nl[project_n-1][0] -=  donation
   print(nl)   

您需要重新分配可以使用 -= 表示法的值:

nl = [[800, 1], [400, 2]]  # each inner list is a fundraising project. the first number in each inner loop refer to the desired amount of money, and the second number is the number of the project

for i in range(3): # there will be 3 donations, the donator will specify to which project and how much money he want to donate
    
    project_n = int(input("Please enter project number (1-5): "))
    donation = int(input("Please enter donation: "))
    nl[project_n][0] -= donation # here

如前所述,您需要使用 -= 运算符。我还建议为此使用字典:

nl = {
    1: {"money": 800},
    2: {"money": 400}
}
for i in range(3):  # there will be 3 donations, the donator will specify to which project and how much money he want to donate

    project_n = int(input("Please enter project number (1-5): "))
    donation = int(input("Please enter donation: "))
    nl[project_n]["money"] -= donation
nl = [[800, 1], [400, 2]]  # each inner list is a fundraising project. the first number in each inner loop refer to the desired amount of money, and the second number is the number of the project
donate = True
while donate == True: 
    project_n = int(input("Please enter project number (1-5): "))
    donation = int(input("Please enter donation: "))
    nl[project_n][0] = nl[project_n][0] - donation
    anotherdonation = input("Do you want to donate to another project (Yes or No): ")
    if anotherdonation == "No":
        donate = False
    else :
        project_n = int(input("Please enter project number (1-5): "))
        donation = int(input("Please enter donation: "))
        nl[project_n][0] = nl[project_n][0] - donation
        anotherdonation = input("Do you want to donate to another project (Yes or No): ")

这是处理此问题的另一种方法,以防捐助者只为一个筹款活动捐款。我不确定你的评论是否必须给三个。还要注意 python 从 0 开始计数,因此要么将输入更改为 0-4,要么在代码中确保减去 1。