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

如何在Python中对嵌套列表指定元素求和并保留不匹配项?

Solution for Merging Nested Lists with Matching First/Second Values

Hey there! The issue with your current code is that it only captures elements where there's a match between first and second, but it doesn't track which elements have been paired or include the ones that don't have a matching counterpart. Let's fix this with two practical approaches:


Approach 1: Using a Dictionary (Efficient, No Order Guarantee)

This method uses a dictionary to track the sum of the third values for each unique pair of first/second values. It's efficient (runs in O(n+m) time where n and m are the lengths of your two lists) and automatically handles both matching and non-matching elements.

first = [[1,1,5],[2,3,7],[3,5,2],[4,4,6]]
second = [[1,1,3],[4,2,4],[2,3,2]]

# Use a dictionary to map (first_val, second_val) pairs to their total sum
sum_map = {}

# Populate the dictionary with elements from the first list
for item in first:
    key = (item[0], item[1])
    sum_map[key] = sum_map.get(key, 0) + item[2]

# Update the dictionary with elements from the second list
for item in second:
    key = (item[0], item[1])
    sum_map[key] = sum_map.get(key, 0) + item[2]

# Convert the dictionary back to the required list format
result = [[pair[0], pair[1], total] for pair, total in sum_map.items()]

print(result)

Output:

[[1, 1, 8], [2, 3, 9], [3, 5, 2], [4, 4, 6], [4, 2, 4]]

Approach 2: Preserving Original Element Order

If you need to keep the order of elements (first including all elements from first in their original order, then adding unmatched elements from second), use this method. It tracks which elements from second have been matched so we don't add them twice.

first = [[1,1,5],[2,3,7],[3,5,2],[4,4,6]]
second = [[1,1,3],[4,2,4],[2,3,2]]

result = []
matched_second_indices = set()

# Process elements from the first list, checking for matches in second
for item in first:
    match_found = False
    for idx, sec_item in enumerate(second):
        if item[0] == sec_item[0] and item[1] == sec_item[1]:
            # Add merged element if match exists
            result.append([item[0], item[1], item[2] + sec_item[2]])
            matched_second_indices.add(idx)
            match_found = True
            break
    if not match_found:
        # Add the original element if no match
        result.append(item)

# Add unmatched elements from the second list
for idx, sec_item in enumerate(second):
    if idx not in matched_second_indices:
        result.append(sec_item)

print(result)

Output:

[[1, 1, 8], [2, 3, 9], [3, 5, 2], [4, 4, 6], [4, 2, 4]]

Key Notes:

  • The dictionary approach is better for larger lists since it avoids nested loops (which run in O(n*m) time).
  • The ordered approach ensures elements appear in the same sequence as they did in the original lists.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:43:13