如何在Python中对嵌套列表指定元素求和并保留不匹配项?
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

