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

如何编写函数移除列表元素?实现通讯录指定联系人完整删除

Hey there! Let's work through fixing your contact removal feature step by step—your core idea makes sense, but we need to adjust how you interact with the agenda list since each contact is a sublist, not individual string entries.

First, let's break down what's going wrong in your current code:

  • In the option == 2 block, you're doing agenda.append(name)—that adds the name as a new entry instead of removing anything, which is the opposite of what you want.
  • Your remove function has a few key issues:
    • The agenda list holds sublists like ["Alice", "12345", "alice@example.com"], not standalone names. So agenda.index(name) will throw an error because the name isn't a direct element of agenda.
    • The pop() method only takes one index argument at a time—you can't pass three indices to it.
    • Your loop logic is looping through each contact but trying to find the index of a name that doesn't exist as a top-level element, which won't work.

Here's the corrected approach

Let's start with a clean remove_contact function, then fix the main loop to use it properly.

1. The Correct Removal Function

Since each contact is a sublist where the first element is the name, we can either:

  • Filter the list to keep only contacts that don't match the target name (cleanest approach with list comprehensions), or
  • Iterate backward through the list to remove matching entries (good if you want to modify the list in-place).

Option 1: Using list comprehension (returns a new filtered list)

def remove_contact(target_name, agenda):
    # Strip whitespace and ignore case for better user experience
    target = target_name.strip().lower()
    # Keep only contacts where the name doesn't match the target
    return [contact for contact in agenda if contact[0].strip().lower() != target]

Option 2: Modify the list in-place (iterate backward to avoid index bugs)

def remove_contact(target_name, agenda):
    target = target_name.strip().lower()
    # Iterate backward so removing items doesn't shift the indices of remaining entries
    for i in range(len(agenda)-1, -1, -1):
        if agenda[i][0].strip().lower() == target:
            agenda.pop(i)

2. Fix the Main Loop

Now update your main loop to use this function instead of appending the name to the agenda. Also, let's fix a few other minor issues (like storing phone numbers as strings instead of integers, since phone numbers often have leading zeros or country codes):

import taskk  # Keeping your existing module import
agenda = []
count = 0

def remove_contact(target_name, agenda):
    target = target_name.strip().lower()
    return [contact for contact in agenda if contact[0].strip().lower() != target]

while True:
    print('---MENU---')
    print('Register- 1 / Remove - 2')
    # Add error handling for non-numeric input
    try:
        option = int(input('Enter your choice: '))
    except ValueError:
        print("Oops, please enter a valid number (1 or 2)!")
        continue

    if option == 1:
        name = input('Name: ').strip()
        # Store phone number as string to preserve leading zeros/formatting
        phone = input('Number: ').strip()
        email = input('Enter email: ').strip()
        contact = [name, phone, email]
        agenda.append(contact)
        count += 1
        print(f"Successfully registered contact: {name}")
    elif option == 2:
        name_to_remove = input('Who do you want to remove? ').strip()
        original_length = len(agenda)
        # Update the agenda with the filtered list
        agenda = remove_contact(name_to_remove, agenda)
        # Give feedback to the user
        if len(agenda) < original_length:
            print(f"Removed all contacts named {name_to_remove}!")
        else:
            print(f"No contact found with the name {name_to_remove}")
    else:
        print("Invalid option—please choose 1 or 2.")

    if count == 2:
        break

# Optional: Print the final agenda to verify
print("\nFinal Contact List:")
for idx, contact in enumerate(agenda, 1):
    print(f"{idx}. Name: {contact[0]}, Phone: {contact[1]}, Email: {contact[2]}")

Key Improvements Explained

  • Phone numbers as strings: Storing them as integers would drop leading zeros (like 01234 becomes 1234) and break numbers with country codes (like +12345). Using strings fixes this.
  • Whitespace handling & case insensitivity: Using strip() and lower() ensures users don't run into issues if they accidentally add spaces or use different capitalization (e.g., "John" vs "john").
  • User feedback: The code now tells the user if the removal succeeded or if no matching contact was found.
  • Error handling: Prevents crashes if the user enters a non-numeric option.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:59:45