如何在组合期间更新列表?
How to update a list during a combination?
我想比较列表的元素,在每个 for
循环结束时,组合会恢复为新的更新列表。
from itertools import combinations
aListe = ['a', 'b', 'c', 'd']
for first, second in combinations(aListe, 2):
# do something
aListe.remove(first)
ValueError: list.remove(x): x not in list
更具体的例子 # do something.
假设我的列表包含 shapely 多边形,例如
aListe = [polygon1, polygon2, polygon3, polygon4]
for first, second in combinations(aListe, 2):
if area(first) > area(second):
aListe.remove(first)
如果列表中第一个多边形的面积已经大于第二个,我不想将它与其他多边形进行比较。我希望下一个 for
循环从没有第一个多边形的更新列表开始。
如您所见,您的代码失败是因为 itertools.combinations
多次访问每个列表项并且它只能被删除一次(假设它只包含一次)。
但是,即使您添加了 if first in aList
这样的检查来规避此错误,您也可能会得到意想不到的结果,这通常是在遍历列表时从列表中删除项目的情况,请参阅 Removing from a list while iterating over it.
在您的情况下,我不是从列表中实际删除一个多边形,而是通过将其添加到“已删除”集合来将其标记为“已删除”,如果再次遇到已删除的多边形则跳过迭代。
(请注意,为了将多边形添加到集合中,如果我理解 https://shapely.readthedocs.io/en/stable/manual.html 正确,"[...] 使用几何 id 作为键,因为形状几何本身不可散列.")
from itertools import combinations
removed = set()
aListe = [polygon1, polygon2, polygon3, polygon4]
for first, second in combinations(aListe, 2):
if id(first) in removed:
continue
if area(first) > area(second):
removed.add(id(first))
我想比较列表的元素,在每个 for
循环结束时,组合会恢复为新的更新列表。
from itertools import combinations
aListe = ['a', 'b', 'c', 'd']
for first, second in combinations(aListe, 2):
# do something
aListe.remove(first)
ValueError: list.remove(x): x not in list
更具体的例子 # do something.
假设我的列表包含 shapely 多边形,例如
aListe = [polygon1, polygon2, polygon3, polygon4]
for first, second in combinations(aListe, 2):
if area(first) > area(second):
aListe.remove(first)
如果列表中第一个多边形的面积已经大于第二个,我不想将它与其他多边形进行比较。我希望下一个 for
循环从没有第一个多边形的更新列表开始。
如您所见,您的代码失败是因为 itertools.combinations
多次访问每个列表项并且它只能被删除一次(假设它只包含一次)。
但是,即使您添加了 if first in aList
这样的检查来规避此错误,您也可能会得到意想不到的结果,这通常是在遍历列表时从列表中删除项目的情况,请参阅 Removing from a list while iterating over it.
在您的情况下,我不是从列表中实际删除一个多边形,而是通过将其添加到“已删除”集合来将其标记为“已删除”,如果再次遇到已删除的多边形则跳过迭代。
(请注意,为了将多边形添加到集合中,如果我理解 https://shapely.readthedocs.io/en/stable/manual.html 正确,"[...] 使用几何 id 作为键,因为形状几何本身不可散列.")
from itertools import combinations
removed = set()
aListe = [polygon1, polygon2, polygon3, polygon4]
for first, second in combinations(aListe, 2):
if id(first) in removed:
continue
if area(first) > area(second):
removed.add(id(first))