我想知道是否有一种方法可以使用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 group, items in placed_objects.items():
    placed_objects[group] = [x for x in items if not x.collidepoint(mousePos)]

关于python - Python中使用变量进行重复操作的快捷方式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30562288/

10-10 19:43