Home > Net >  Removing elements from sublists in Python
Removing elements from sublists in Python

Time:01-02

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]]]

CodePudding user response:

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]]]

CodePudding user response:

Use list comprehension:

print([[[num for num in subsub_A1 if num not in subsub_J1]
        for subsub_A1, subsub_J1 in zip(sub_A1, sub_J1)]
       for sub_A1, sub_J1 in zip(A1, J1)])

Output:

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

CodePudding user response:

If you have an arbitrary list depth, consider using a recursive function:

def cleanup(A, J):
    for l1, l2 in zip(A, J):
        if l1 and isinstance(l1[0], list):
            cleanup(l1, l2)
        else:
            s = set(l2)
            l1[:] = [x for x in l1 if x not in s]

cleanup(A1, J1) # operation is in place
print(A1)

Output: [[[3, 4, 6], [0, 3, 5]], [[3, 4, 6], [1, 3, 6]]]

CodePudding user response:

Try using remove method if you don't mind corrupting the original data:

from contextlib import suppress

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

for A, J in zip(A1, J1):
    for a, j in zip(A, J):
        for x in j:
            with suppress(ValueError):
                a.remove(x)
print(f"RESULT: {A1}")

output: RESULT: [[[3, 4, 6], [0, 3, 5]], [[3, 4, 6], [1, 3, 6]]]

CodePudding user response:

Using list comprehension

[[list(set(A1[i][j])-set(J1[i][j])) for j in range(0,len(J1))] for i in range(0,len(A1))]

#output

[[[3, 4, 6], [0, 3, 5]], [[3, 4, 6], [1, 3, 6]]]
  • Related