Performing a list operation in Python
Question:
I am removing J1
from J
. Corresponding to the removed indices, I want to alter Ci[1]
and append to Ci
as shown below but I am getting an error. I also present the expected output.
J=[2, 6, 9, 10]
J1=[6,10]
l=[]
l.append(J)
l.append([x for x in J if x not in J1])
Ci = [[0, 0, 0, 0], [10, 30, 50, 80]]
A=Ci[1]([x for x in J if x not in J1])
print(A)
The error is
in <module>
A=Ci[1]([x for x in J if x not in J1])
TypeError: 'list' object is not callable
The expected output is
[[[0, 0, 0, 0], [10, 30, 50, 80]],[[10, 50]]]
Answers:
You can use zip
to iterate on two lists simultaneously:
A = [Ci, [x for x,y in zip(Ci[1],J) if y not in J1]]
print(A)
# [[[0, 0, 0, 0], [10, 30, 50, 80]], [10, 50]]
You can collect the indices first,
lidx = [i for i in range(len(J)) if J[i] not in J1]
A = [Ci, [Ci[1][i] for i in lidx]]
I am removing J1
from J
. Corresponding to the removed indices, I want to alter Ci[1]
and append to Ci
as shown below but I am getting an error. I also present the expected output.
J=[2, 6, 9, 10]
J1=[6,10]
l=[]
l.append(J)
l.append([x for x in J if x not in J1])
Ci = [[0, 0, 0, 0], [10, 30, 50, 80]]
A=Ci[1]([x for x in J if x not in J1])
print(A)
The error is
in <module>
A=Ci[1]([x for x in J if x not in J1])
TypeError: 'list' object is not callable
The expected output is
[[[0, 0, 0, 0], [10, 30, 50, 80]],[[10, 50]]]
You can use zip
to iterate on two lists simultaneously:
A = [Ci, [x for x,y in zip(Ci[1],J) if y not in J1]]
print(A)
# [[[0, 0, 0, 0], [10, 30, 50, 80]], [10, 50]]
You can collect the indices first,
lidx = [i for i in range(len(J)) if J[i] not in J1]
A = [Ci, [Ci[1][i] for i in lidx]]