如何不使用内置函数迭代删除列表第三个元素?多元素场景代码求助
Fixing Your Third-Element Deletion Logic
First, let's spot the key issues in your current code that are causing it to fail when the list has more than 3 elements:
- Incorrect comparison instead of modification: Lines like
v[2]==v[1] and v[1]==v[0]use equality checks (==) instead of assignments, so they don’t change the list at all—they just evaluate toTrueorFalseand do nothing with that result. - Unimplemented logic for longer lists: Your
elseblock doesn’t actually build the new list without the third element; it just runs another useless comparison. - Single-pass instead of iterative deletion: Your current function only attempts to delete once, but your requirement says you need to delete the third element in each iteration until there aren’t enough elements left.
- Global variable dependency: Using global variables like
vcan lead to unexpected side effects; it’s better to pass the list as a parameter to your function.
Here's the Revised Solution
This code will repeatedly remove the third element (without using remove() or other built-in deletion functions) and print the updated list each time, until fewer than 3 elements remain:
def create_array(): n = int(input('Digit total elements in dynamic array - ')) v = [] for i in range(n): element = int(input('Digit element to array - ')) v.append(element) return v def remove_third_element_iteratively(input_list): # Make a copy to avoid modifying the original list current_list = input_list.copy() while True: if len(current_list) < 3: print('There is no element to delete!') break # Build a new list excluding the third element (index 2) # Combine elements before index 2 and elements after index 2 new_list = current_list[:2] + current_list[3:] print(f"After deleting third element: {new_list}") # Update current_list for the next iteration current_list = new_list # Get the user's array user_array = create_array() print(f"Original array: {user_array}") # Run the iterative deletion remove_third_element_iteratively(user_array)
How This Works:
- Copying the input list: We use
.copy()to ensure we don’t alter the original user-provided array. - Loop until too few elements: The
while Trueloop keeps running until the list has fewer than 3 elements. - Manual element exclusion: Instead of using built-in deletion functions, we create a new list by concatenating:
- All elements before the third one (
current_list[:2]—indices 0 and 1) - All elements after the third one (
current_list[3:]—from index 3 to the end)
- All elements before the third one (
- Output each step: After building the new list, we print it so you can see the result of each deletion.
Example Output:
If you input 5 elements: 1, 2, 3, 4, 5
Original array: [1, 2, 3, 4, 5] After deleting third element: [1, 2, 4, 5] After deleting third element: [1, 2, 5] After deleting third element: [1, 2] There is no element to delete!
内容的提问来源于stack exchange,提问作者Luismaia1994
相关产品推荐
相关产品推荐

