1

I got two lists as shown below:
a = [[[1,2], [3, 4], [5,6]], [[8,9],[10,11]]]
b = [[[1,2], [1,3],[2,3],[3, 4],[4,6],[5,6]],[[8,9],[9,10],[10,11]]]

The values in both lists are a group of list of coordinate points. And you can notice that some of the coordinate points in list a are also shown in list b

My goal is to slice list b from the given coordinate points from list a and then append in a new list. Here is an example of what I expect to get.

Example

The first item of list a is [[1,2], [3, 4], [5,6]] which I named as a[0] while that of list b is [[1,2], [1,3],[2,3],[3, 4],[4,6],[5,6]] which I named as b[0]. Therefore, a[0] is a set of b[0]

I want to slice b[0] based on the values in a[0] into a new list which looks like [[[1,2],[1,3],[2,3],[3,4]],[[3, 4],[4,6],[5,6]]]. In other words, a[0] serves as the slicing index of b[0].

Below is my code, and I do not have any idea to execute the above statement.

for items in a:
    c.append([])
    for i,j in zip(range(len(items)),range(len(b))):
        if i < len(items)-1:
            L_i = b[j][b[j].index(a[i]):b[j].index(a[i+1])+1]
            L_i = list(tuple(item) for item in L_i)
        elif i == len(concave_points)-1:
            temp1 = b[j][b[j].index(a[i]):]
            temp2 =b[j][0:b[j].index(a[0])+1]
            L_i = temp1 + temp2
            L_i = list(tuple(item) for item in L_i)

And an error ValueError: [[1, 2], [3, 4], [5, 6]] is not in list is occured.

Thanks a lot.

Hang
  • 197
  • 1
  • 11

2 Answers2

1

You can zip the lists instead of their length and just slice the sublists by index

a = [[[1, 2], [3, 4], [5, 6]], [[8, 9], [10, 11]]]
b = [[[1, 2], [1, 3], [2, 3], [3, 4], [4, 6], [5, 6]], [[8, 9], [9, 10], [10, 11]]]

c = []
for aa, bb in zip(a, b):
    for i in range(len(aa) - 1):
        c.append(bb[bb.index(aa[i]):bb.index(aa[i + 1]) + 1])

print(c) # [[[1, 2], [1, 3], [2, 3], [3, 4]], [[3, 4], [4, 6], [5, 6]], [[8, 9], [9, 10], [10, 11]]]

And as on liner with list comprehensions

c = [bb[bb.index(aa[i]):bb.index(aa[i + 1]) + 1] for aa, bb in zip(a, b) for i in range(len(aa) - 1)]
Guy
  • 46,488
  • 10
  • 44
  • 88
0
a = [[1, 2], [3, 4], [5, 6]]
b = [[1, 2], [1, 3], [2, 3], [3, 4], [4, 6], [5, 6]]
union_a_b = []

a.extend(b)

for pair in a: 
    if pair not in union_a_b: 
        union_a_b.append(pair)
    else: 
        continue

print(union_a_b)