You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向多维数组的对应子列表中添加扩展值

Fixing Donation Amount Addition to Correct Donor Sublist

Hey there! Let's tackle that issue where your donation amounts are getting appended to the main data_list instead of the right donor's sublist. I'll walk you through the key problems in your current code and show you how to fix them.

Key Issues in Your Current Code

  • Broken name_found check: Right now, your loop over data_list resets name_found every iteration. That means only the last entry in the list determines if the name exists—if the donor is earlier in the list, you'll incorrectly mark them as not found.
  • Incorrect new donor initialization: When adding a new donor, you're only appending [full_name] instead of matching the 4-column structure of existing entries (Name, Total Donation, Number of Gifts, Avg Gift).
  • Wrong target for donation amount: data_list.append(donation_amt) adds the amount to the main list, not the donor's specific sublist.

Corrected Code Implementation

Here's the fixed version of your addtolist() function with explanations of the key changes:

spacing = '- ' * 45  # formatting for DONOR header
data_list = [['NAMES', 'DONATION AMOUNT', 'Number of Gifts', 'Avg Gifts'], 
             ['Rudolph S', 1500, 3, 500],  # Pre-calculated avg for example
             ['Josef M', 250, 5, 50],
             ['Joye A', 5000, 2, 2500],
             ['Joni M', 2750, 1, 2750],
             ['Rachelle L', 750, 3, 250],
             ['Vena U', 1000, 7, round(1000/7, 2)],
             ['Efrain L', 10000, 1, 10000],
             ['Mee H', 15000, 2, 7500],
             ['Tanya E', 50000, 1, 50000],
             ['Garrett H', 800, 2, 400]]

def addtolist():
    """Method for sending 'Thank You' messages to Donors, using names"""
    while True:
        print("Enter the name of the person you are writing to (or enter 'list' to see a list of names or Q to quit) ")
        fname_prompt = input("First Name: ").strip().capitalize()
        if fname_prompt.upper() == "Q":
            break
        elif fname_prompt.lower() == "list":
            # Simplified list printing (fixed original logic issues)
            print(spacing)
            print('{:>44s}'.format(data_list[0][0]))
            print(spacing)
            # Print donors in pairs
            donors = data_list[1:]
            for i in range(0, len(donors), 2):
                if i+1 < len(donors):
                    print('{:>30s}'.format(donors[i][0]), '{:>35s}'.format(donors[i+1][0]))
                else:
                    print('{:>30s}'.format(donors[i][0]))
            continue
        
        lname_prompt = input("Last Name: ").strip().capitalize()
        if lname_prompt.upper() == "Q":
            break
        elif lname_prompt.lower() == "list":
            # Reuse the same list printing logic as above
            print(spacing)
            print('{:>44s}'.format(data_list[0][0]))
            print(spacing)
            donors = data_list[1:]
            for i in range(0, len(donors), 2):
                if i+1 < len(donors):
                    print('{:>30s}'.format(donors[i][0]), '{:>35s}'.format(donors[i+1][0]))
                else:
                    print('{:>30s}'.format(donors[i][0]))
            continue
        
        full_name = f"{fname_prompt} {lname_prompt}"
        donor_index = -1
        
        # Find if the donor exists and get their index
        for idx, vals in enumerate(data_list[1:]):  # Skip header row
            if vals[0] == full_name:
                donor_index = idx + 1  # Adjust for header row
                break
        
        if donor_index == -1:
            add_name = input(f"That name is not in the Donor list. Do you want to add {full_name} to the list? ").upper()
            if add_name == "Y":
                # Initialize new donor with 4 columns matching existing structure
                data_list.append([full_name, 0, 0, 0])
                donor_index = len(data_list) - 1  # Get index of new donor
                # Print updated donor list
                print(spacing)
                print('{:>44s}'.format(data_list[0][0]))
                print(spacing)
                donors = data_list[1:]
                for i in range(0, len(donors), 2):
                    if i+1 < len(donors):
                        print('{:>30s}'.format(donors[i][0]), '{:>35s}'.format(donors[i+1][0]))
                    else:
                        print('{:>30s}'.format(donors[i][0]))
        
        # Now handle the donation amount
        donation_amt = int(input(f"Enter in the donation amount from Donor {full_name}: $"))
        print(f'{full_name} has donated ${donation_amt}')
        
        # Update the donor's sublist
        donor_sublist = data_list[donor_index]
        donor_sublist[1] += donation_amt  # Add to total donation amount
        donor_sublist[2] += 1  # Increment number of gifts
        # Calculate average gift (round to 2 decimal places for currency)
        donor_sublist[3] = round(donor_sublist[1] / donor_sublist[2], 2)
        
        print("\nUpdated Donor List:")
        for row in data_list:
            print(row)

Key Changes Explained

  1. Fixed Donor Lookup: Used enumerate() to track the index of the donor in data_list (skipping the header row). This lets us directly access their sublist later.
  2. Proper New Donor Initialization: When adding a new donor, we append a full 4-element list [full_name, 0, 0, 0] to match the existing data structure.
  3. Targeted Donation Update: Instead of appending to the main list, we grab the donor's sublist using donor_index, then:
    • Add the donation amount to the total (donor_sublist[1])
    • Increase the number of gifts (donor_sublist[2])
    • Recalculate the average gift amount (donor_sublist[3])
  4. Simplified List Printing: Cleaned up the donor list printing logic to avoid the original modulus and range errors, making it easier to read and maintain.

Now when you add a donation, it will correctly update the corresponding donor's entry instead of adding to the main list!

内容的提问来源于stack exchange,提问作者McBraunie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:07:57