Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements from sublists in Python

Tags:

python

list

I have two lists A1 and J1 containing many sublists. From each sublist of A1[0], I want to remove the element specified in J1[0]. I present the current and expected outputs.

A1 = [[[1, 3, 4, 6], [0, 2, 3, 5]], [[1, 3, 4, 6], [1, 3, 4, 6]]]

J1 = [[[1], [2]], [[1], [4]]]

arD = []


for i in range(0,len(A1)):
    for j in range(0,len(J1)):
        C=set(A1[i][j])-set(J1[i][j])
        D=list(C)
        arD.append(D)
        D=list(arD)
print("D =",D)

The current output is

D = [[3, 4, 6], [0, 3, 5], [3, 4, 6], [1, 3, 6]]

The expected output is

D = [[[3, 4, 6], [0, 3, 5]],[[3, 4, 6],[1, 3, 6]]]
like image 951
jcbose123 Avatar asked Oct 28 '25 02:10

jcbose123


1 Answers

Code:-

A1 = [[[1, 3, 4, 6], [0, 2, 3, 5]], [[1, 3, 4, 6], [1, 3, 4, 6]]]

J1 = [[[1], [2]], [[1], [4]]]

arD=[]

for i in range(0,len(A1)):
    tmp=[]                 #Created a tmp variable list
    for j in range(0,len(J1)):
        C=set(A1[i][j])-set(J1[i][j])
        tmp.append(list(C))    #Appending result in tmp variable
    arD.append(tmp)            #Storing tmp list as a list of lists in arD.
print("D =",arD)

Output:-

D = [[[3, 4, 6], [0, 3, 5]], [[3, 4, 6], [1, 3, 6]]]
like image 166
Yash Mehta Avatar answered Oct 29 '25 16:10

Yash Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!