Python - 筛选列表中对象的引用
Python - reference of objects in filtered list
我在 python
中有这个 Hero
对象
class Hero:
def __init__(self, json_def, player_index):
self._alive = True
... # other attributes
然后,我有 Hero
对象的列表,即
Heroes = [HeroObj1, HeroObj2, HeroObj3, HeroObj4]
我想做的是过滤列表并获取对象引用,而不是对象的副本。我知道我可以像下面那样进行过滤。
filtered_list = [x for x in Heroes if x.alive]
但是,这种方法会导致将过滤后的对象复制到 filtered_list
。我想做参考,这样我就可以在修改这个过滤版本时修改初始列表(Heroes
)/filtered_list
(例如,只修改活着的英雄)。
是否有任何解决方案可以实现我正在寻找的目标?
如有任何帮助,我们将不胜感激!干杯!
也许我误解了你的问题,但 filtered_list
中的项目已经是对 Heroes
中保存的相同对象的引用。尚未创建对象的副本。
如果访问 heroes
中的对象,对 filtered_list
中对象的修改也将可见,因为它们引用相同的对象。
>>> h = Hero()
>>> l1 = [h]
>>> l2 = [x for x in l1 if x._alive]
>>> l1[0] is l2[0] # are they same object?
True
>>> l2[0]._active = False
>>> l1[0]._active
False
>>> l1[0] is l2[0] # are they still same object?
True
它们是同一个对象,因此列表存储的是对对象的引用,而不是对象本身,并且列表理解不会创建对象的副本。
我在 python
中有这个Hero
对象
class Hero:
def __init__(self, json_def, player_index):
self._alive = True
... # other attributes
然后,我有 Hero
对象的列表,即
Heroes = [HeroObj1, HeroObj2, HeroObj3, HeroObj4]
我想做的是过滤列表并获取对象引用,而不是对象的副本。我知道我可以像下面那样进行过滤。
filtered_list = [x for x in Heroes if x.alive]
但是,这种方法会导致将过滤后的对象复制到 filtered_list
。我想做参考,这样我就可以在修改这个过滤版本时修改初始列表(Heroes
)/filtered_list
(例如,只修改活着的英雄)。
是否有任何解决方案可以实现我正在寻找的目标?
如有任何帮助,我们将不胜感激!干杯!
也许我误解了你的问题,但 filtered_list
中的项目已经是对 Heroes
中保存的相同对象的引用。尚未创建对象的副本。
如果访问 heroes
中的对象,对 filtered_list
中对象的修改也将可见,因为它们引用相同的对象。
>>> h = Hero()
>>> l1 = [h]
>>> l2 = [x for x in l1 if x._alive]
>>> l1[0] is l2[0] # are they same object?
True
>>> l2[0]._active = False
>>> l1[0]._active
False
>>> l1[0] is l2[0] # are they still same object?
True
它们是同一个对象,因此列表存储的是对对象的引用,而不是对象本身,并且列表理解不会创建对象的副本。