I have had to edit this question for the third time and present the data as simply as possible. I suppose the last one seemed very complex to recognize the pattern. Here is what I have now which looks more like the first one, for which @Andrej provided a solution, but I was unable to adapt to my scenario. I suppose that would go down to his conditions for merging. The original
data is 3-D and is given below.`
original = [
[[0,1],[2,3],[4,5]],
[[0,1],[4,5]],
[[2,3]],
[[6,7],[8,9],[10,11]],
[[8,9],[6,7]],
[[6,7],[10,11]],
[[16,17],[12,13],[14,15]],
[[12,13]],
[[14,15],[16,17],[18,19]]
[[12,13],[16,17],[20,21]]
]
`
From the given data, I want to obtain another 3-D merged
data`
merged = [
[[0,1],[2,3],[4,5]],
[[6,7],[8,9],[10,11]],
[[12,13],[14,15],[16,17],[18,19],[20,21]]
]
. I need to loop over all the 2-D list and merge all 2-D lists with common 1-D inner lists, while removing any duplicate 1-D lists. More like finding 2-D lists that have intersecting lists, and then merging all such 2-D lists. From the given original
data, the first 2-D list intersects with the second through the list [0,1],[4,5]
while the third 2-D list intersects with the first via [2,3]
. Together, all three 2-D lists form a connected chain via their intersecting 1-D lists. This chain should be merged into a union of all three 2-D lists ie [[0,1],[2,3],[4,5]]
. I have tried the sample code below:
import numpy as np
original = [
[[0, 1], [2, 3], [4, 5]],
[[0, 1], [4, 5]],
[[2, 3]],
[[6, 7], [8, 9], [10, 11]],
[[8, 9], [6, 7]],
[[6, 7], [10, 11]],
[[16, 17], [12, 13], [14, 15]],
[[12, 13]],
[[14, 15], [16, 17], [18, 19]],
[[12, 13], [16, 17], [20, 21]]
]
tmp = {}
for subl in original:
for a, b in subl:
tmp.setdefault(a, set()).add(b)
merged = []
for k, v in tmp.items():
out.append([[k, i] for i in v])
print(merged)
But this is not giving the expected merged data as given above but this: [[[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2], [2, 3], [2, 4]]]
. Any help would be hugely appreciated, please.
Try:
original = [
[[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]],
[[0, 1], [0, 2], [0, 3], [0, 4], [0, 5]],
[[0, 2], [0, 3], [0, 5]],
[[1, 0], [1, 2], [1, 4]],
[[1, 2], [1, 3], [1, 4]],
[[1, 0], [1, 2], [1, 3], [1, 4]],
[[1, 0]],
[[1, 0], [1, 3]],
[[2, 0], [2, 1], [2, 2], [2, 3]],
[[2, 1], [2, 2], [2, 3], [2, 4]],
[[2, 2], [2, 3], [2, 4]],
[[2, 3], [2, 4]],
[[2, 4]],
]
tmp = {}
for subl in original:
for a, b in subl:
tmp.setdefault(a, set()).add(b)
out = []
for k, v in tmp.items():
out.append([[k, i] for i in v])
print(out)
Prints:
[
[[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5]],
[[1, 0], [1, 2], [1, 3], [1, 4]],
[[2, 0], [2, 1], [2, 2], [2, 3], [2, 4]],
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.