Python 中用于变量重复操作的快捷方式?

Shortcut in Python for repetitive actions with variables?

我想知道是否有一种方法可以使用 Python 以更短的方式表达以下代码。有 placedWallplacedFlyerplacedSpringplacedDiamonds。并且,placedWallListplacedFlyerListplacedSpringListplacedDiamondsList。我想这样做是因为我要添加更多具有相同重复操作的对象,这会使我的代码变得不必要地长。

for placedWall in placedWallList:
    if placedWall.rect.collidepoint(mousePos):
        placedsprites.remove(placedWall)
        placedWallList.remove(placedWall)
for placedFlyer in placedFlyerList:
    if placedFlyer.rect.collidepoint(mousePos):
        placedsprites.remove(placedFlyer)
        placedFlyerList.remove(placedFlyer)
for placedSpring in placedSpringList:
    if placedSpring.rect.collidepoint(mousePos):
        placedsprites.remove(placedSpring)
        placedSpringList.remove(placedSpring)
for placedDiamonds in placedDiamondsList:
    if placedDiamonds.rect.collidepoint(mousePos):
        placedsprites.remove(placedDiamonds)
        placedDiamondsList.remove(placedDiamonds)

只需遍历列表:

for item_list in (placedWallList, placedFlyerList, placedSpringList, placedDiamondsList):
    for item in item_list:
        if item.rect.collidepoint(mousePos):
            placedsprites.remove(item)
            item_list.remove(item)

但是,请注意最后一行在遍历列表时改变了列表的长度,这是一个非常糟糕的主意!这将导致 after 项目被跳过,并且可能导致列表末尾出现 IndexError

您可能想将所有列表放在一个字典中 {'walls': […], 'flyers': […], …} 并试试这个:

for group, items in placed_objects.items():
    placed_objects[group] = [x for x in items if not x.collidepoint(mousePos)]