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

时间:2015-05-31 20:24:49

标签: python performance object action shortcut

我想知道是否有办法使用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)

2 个答案:

答案 0 :(得分:5)

只需遍历列表:

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)

但是,请注意,最后一行在迭代它时会改变列表的长度,这是一个非常糟糕的主意!这将导致之后刚删除的项被跳过,并且可能会导致列表末尾的IndexError

答案 1 :(得分:1)

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

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