Reputation: 1723
I have two lists in python, they contain points, and I want to remove from BOTH lists any permutation that exists in both lists.
I tried writing the followiing code that fails:
for indexA, pointA in enumerate(listA):
for indexB, pointB in enumerate(listB):
if isPermutation(listA[indexA],listB[indexB]):
del listA[indexA]
del listB[indexB]
This of course would not work because the del
command creates a new list and the for loop will loose the reference to both lists (not to mention it takes O(n) to remove from a list in python).
There are various ways to do this when you have one list which are mentioned here. But they don't seem to be helpful when working with two lists with the dependency above.
Could anyone supply code/a way to do this?
I care about speed.
Note: Building the list using .append() is really slow due to the fact its amortized.
Upvotes: 0
Views: 215
Reputation: 845
instead of doing it the way markusian say, you could make new listA and listB directly instead of making a listC to compare and there isn't really a need for enumerate is there?
removing the enumerate cause it isn't really needed cause it in a loop will speed it up a little.
listC = []
listD = []
for pointA in listA:
for pointB in listB:
if not isPermutation(pointA,pointB):
listC.append(pointA)
listD.append(pointB)
else:
# fix B to look like A in new listA (listC) and listB (listD)
listC.append(pointB)
listD.append(pointB)
then if you want, you could just replace the old list with the new
listA = listC
listB = listD
edit1: if you really must avoid append, you could do it this way, although, it slower on small list, not so sure about big list:
listC = []
listD = []
for pointA in listA:
for pointB in listB:
if not isPermutation(pointA,pointB):
# a += b is like a = a + b
listC += [pointA]
listD += [pointB]
else:
# fix B to look like A in new listA (listC) and listB (listD)
listC += [pointB]
listD += [pointB]
Upvotes: 0
Reputation: 3070
I would suggest first to create another list containing the elements to be deleted from the initial lists, say listC
and then use list comprehension to modify both listA
and listB
.
For instance, after having obtained listC:
listA = [a for a in listA if a not in listC]
listB = [a for a in listB if a not in listC]
Upvotes: 1