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

如何解决索引与循环相关问题?求实现指定规则的列表求和函数

Sum Unique Index Elements from l1 Using l2

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

  1. 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.
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:06:49