如何在Python中查找多个二维数组中的重复元素并保存坐标
Sure thing! Finding common elements across multiple 2D arrays in Python is totally doable, and sets are your best friend here because they make membership checks and intersections super straightforward. Let me walk you through how to solve this with your example, and also scale it for any number of arrays (like your ArrayN):
Step-by-Step Solution
1. Convert Sublists to Tuples
First, we need to convert each sublist in your 2D arrays to tuples. Why? Because lists are unhashable and can't be stored in sets, but tuples (being immutable) can. This lets us use set operations to find overlaps easily.
2. Compute the Intersection of All Sets
The intersection of multiple sets gives us elements that exist in every single set. We can do this directly for a small number of arrays, or use reduce to handle any number of arrays dynamically.
Example Code for Your Specific Arrays
# Define your input arrays array1 = [[1, 7], [2, 7], [3, 7], [4, 7], [5, 7], [6, 7], [7, 7]] array2 = [[5, 8], [5, 7], [5, 6], [5, 5], [5, 4]] array3 = [[1, 7], [2, 7], [3, 7], [4, 7], [5, 7], [6, 7], [7, 7]] # Convert each 2D array into a set of tuples set1 = set(tuple(sub) for sub in array1) set2 = set(tuple(sub) for sub in array2) set3 = set(tuple(sub) for sub in array3) # Find elements present in all three sets common_elements = set1.intersection(set2, set3) # Convert the result back to a list of lists (matching your desired output format) array_result = [list(item) for item in common_elements] print(array_result) # Output: [[5, 7]]
Scaling to Any Number of Arrays (ArrayN)
If you have more than 3 arrays, you can use functools.reduce to compute the intersection across all sets in a loop:
from functools import reduce # Collect all your 2D arrays into a single list all_arrays = [array1, array2, array3] # Add ArrayN and others here # Convert each array to a set of tuples all_sets = [set(tuple(sub) for sub in arr) for arr in all_arrays] # Calculate the intersection of all sets common_elements = reduce(lambda a, b: a.intersection(b), all_sets) # Convert back to list of lists array_result = [list(item) for item in common_elements]
Key Notes
- This method works for any number of 2D arrays—just add all your arrays to the
all_arrayslist. - The result will include every sublist that appears in every input array, which matches exactly what you're asking for.
- Converting to tuples is a quick, efficient step that enables the set operations under the hood.
内容的提问来源于stack exchange,提问作者Duarte Somsen

