I have
JavaScript
x
4
1
listB=[[0,1],[1,2]]
2
3
listall=[0,1,2,3]
4
For each element in listB
, I want to extend it to a length-3 element by adding a number that is in listall
but not in this element. My desired output is the following list:
JavaScript
1
2
1
listC=[[0,1,2],[0,1,3],[1,2,3]]
2
As a first step, I tried the following code:
JavaScript
1
11
11
1
import numpy as np
2
3
listB=[[0,1],[1,2]]
4
listall=range(4)
5
listC=[]
6
for b in listB:
7
difb=set(listall)-set(b)
8
for i in difb:
9
listC.append([b,i])
10
print(listC)
11
However, the output I got is:
JavaScript
1
2
1
[[[0,1],2],[[0,1],3],[[1,2],0],[[1,2],3]]
2
This is far from what I wanted. As each element in this output list has a subarray nested in it, also the numbers in each element are not ordered. I need to at least turn it to [[0,1,2],[0,1,3],[0,1,2],[1,2,3]] first (and then get rid of the duplicates). What’s the fastest (most efficient) way to achieve it? Thanks!
Advertisement
Answer
You need to unpack the items in b
when creating the new list
JavaScript
1
2
1
listC.append([*b,i])
2
or if its easier to understand, add a new list with i to list b
JavaScript
1
2
1
listC.append(b + [i])
2