Home > database >  Removing elements and corresponding indices in Python
Removing elements and corresponding indices in Python

Time:07-11

I have two lists A and B. I want to remove the zero elements of A and the corresponding indices in B. I present the expected output.

A = [[210.9, 0.0, 1109.68564358, 383.43369921, 0.0]]
B=[[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)]]

The expected output is

Anew= [[210.9, 1109.68564358, 383.43369921]]
Bnew= [[(0, 0), (0, 2), (0, 3)]]

CodePudding user response:

These are list of list, better to convert them to normal list first:

A = [[210.9, 0.0, 1109.68564358, 383.43369921, 0.0]]
B = [[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)]]

# convert them to just list
A = A[0] 
B = B[0]

Anew = [a for a in A if a!=0.0]
Bnew = [b for a,b in zip(A,B) if a!=0.0]

# back to list of list, probably unnecessary.
Anew = [Anew] 
Bnew = [Bnew]

Anyway, for this sort of task it may be better to use pandas.

  • Related