我正在尝试基于另一组创建一组,并且只排除一个项目... (使用集合内的对象在另一个 for 循环内执行 for 循环,但在第二个循环中不迭代自身)
代码:
for animal in self.animals:
self.exclude_animal = set((animal,))
self.new_animals = set(self.animals)
self.new_animals.discard(self.exclude_animal) # parameters for a set needs to be a set?
for other_animal in (self.new_animals):
if animal.pos[0] == other_animal.pos[0]:
if animal.pos[1] == other_animal.pos[1]:
self.animals_to_die.add(animal)
print other_animal
print animal
self.animals_to_die.add(other_animal)
要点是,我的 print 语句返回对象 id(x)
,所以我知道它们是同一个对象,但它们不应该是,我在那个集合 new_animals 上丢弃了它
设置。
关于为什么这不排除该项目的任何见解?
最佳答案
set.discard()
从集合中删除 一个 项,但您传入了整个集合对象。
您需要删除元素本身,而不是另一个包含该元素的集合:
self.new_animals.discard(animal)
演示:
>>> someset = {1, 2, 3}
>>> someset.discard({1})
>>> someset.discard(2)
>>> someset
set([1, 3])
请注意 2
是如何被删除的,但 1
仍保留在集合中。
在这里循环遍历集合差异会更容易:
for animal in self.animals:
for other_animal in set(self.animals).difference([animal]):
if animal.pos == other_animal.pos:
self.animals_to_die.add(animal)
print other_animal
print animal
self.animals_to_die.add(other_animal)
(我假设 .pos
是两个值的元组,您可以在这里测试直接相等性)。
您不需要一直在self
上存储new_animals
;使用本地名称就足够了,这里甚至不需要。
关于python - 复制一组并排除一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19956878/