如何解决索引与循环相关问题?求实现指定规则的列表求和函数
Got it, let's break down how to solve this problem. The key here is to avoid counting duplicate indices from l2, so first we need to get the unique values from l2, then sum the corresponding elements in l1.
Approach
- Remove duplicates from l2: Convert l2 into a set—sets automatically eliminate duplicate values, which is perfect because we only want each index counted once.
- Sum the corresponding elements: Iterate over each unique index in the set, grab the element from l1 at that index, and add them all up.
Solution Code
Here's a clean, efficient implementation in Python:
def sum_unique_indices(l1, l2): # Convert l2 to a set to get unique indices unique_indices = set(l2) # Sum the elements in l1 for each unique index return sum(l1[idx] for idx in unique_indices)
Example Test
Let's test this with your sample input:
l1 = [11, 2, 0, -4, 3] l2 = [0, 1, 3, 0] print(sum_unique_indices(l1, l2)) # Output: 10
This works because set(l2) becomes {0, 1, 3}, and summing l1[0] + l1[1] + l1[3] gives 11 + 2 + (-4) = 10, which matches your expected result.
Optional: Handling Invalid Indices (Just in Case)
While the problem states l2 elements are valid indices (in [0, len(l1))), if you want to make the function more robust against invalid inputs, you can add a check to skip any indices that are out of bounds:
def sum_unique_indices(l1, l2): unique_indices = set(l2) return sum(l1[idx] for idx in unique_indices if 0 <= idx < len(l1))
This way, even if l2 has invalid indices, they won't cause an error—they'll just be ignored.
That's it! This approach is efficient (O(n) time where n is the length of l2, since converting to a set is O(n) and summing is O(k) where k is the number of unique indices, which is <=n) and easy to read.
内容的提问来源于stack exchange,提问作者Alessandro Anderson

