如何删除列表1中与列表2重复的索引并正确计算剩余索引的和(解决元素重复场景下代码失效问题)
Hey there, let's break down why your code fails with duplicate values in list1 and fix it properly.
The Root Cause of the Problem
Your code uses a.index(i) to generate indices for list1 (a), but this method has a critical flaw: it only returns the first occurrence of an element. When list1 has duplicate values (like all 6s), every call to a.index(i) returns 0, so your x list becomes [0,0,0,0,0,0,0] instead of the actual indices [0,1,2,3,4,5,6].
On top of that, the line y = [b.index(j) for j in b] is unnecessary and misleading—it's getting the indices of elements within list2 (b), not the indices you want to remove from list1. This is why your normal example works by accident (the indices of b happened to match the indices you wanted to remove from a), but it breaks completely with duplicates.
The Fix
We need to:
- Generate the actual indices of
list1directly (not relying on element values). - Filter out any indices that exist in
list2. - Sum the remaining indices.
Here's the corrected code that works for both normal and duplicate scenarios:
# Example with duplicate values a = [6,6,6,6,6,6,6] b = [0,2,4] # Generate all real indices of list1 all_indices = list(range(len(a))) # Keep only indices NOT present in list2 remaining_indices = [idx for idx in all_indices if idx not in b] # Calculate the sum print(sum(remaining_indices)) # Output: 15 (1+3+5+6 = 15)
And for your original normal scenario (aligned with your stated requirement):
a = [1,2,3,4,5] b = [0,2,4] # Indices to remove from a all_indices = list(range(len(a))) remaining_indices = [idx for idx in all_indices if idx not in b] print(sum(remaining_indices)) # Output: 4 (1+3 = 4)
(Note: Your original normal scenario code output 7 because it was removing indices of list2 instead of using list2 values as indices to remove. The code above fixes this to match your stated requirement.)
Key Improvements
- Direct Index Generation:
range(len(a))gives us the true indices of every element inlist1, regardless of duplicate values. - Efficient Filtering: List comprehensions are faster and cleaner than looping with
remove(), which can cause bugs when modifying a list while iterating over it. - Clear Intent: The code directly reflects your requirement of removing indices from
list1that exist inlist2.
内容的提问来源于stack exchange,提问作者ATISE

