0


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.

4

2 回答 2

1

我建议首先创建另一个列表,其中包含要从初始列表中删除的元素,例如listC,然后使用列表推导来修改listAlistB。例如,在获得 listC 之后:

listA = [a for a in listA if a not in listC]
listB = [a for a in listB if a not in listC]
于 2013-07-28T20:51:03.890 回答
0

而不是像markusian所说的那样做,你可以直接制作新的listA和listB,而不是制作一个listC来比较,真的不需要枚举吗?

删除 enumerate 因为它并不是真正需要的,因为它在循环中会加快一点速度。

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)

那么如果你愿意,你可以用新列表替换旧列表

listA = listC
listB = listD

编辑1:如果你真的必须避免追加,你可以这样做,虽然,它在小列表上较慢,对大列表不太确定:

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]
于 2013-07-28T22:14:48.007 回答