我试图在另一个集合中创建一个集合,并且只排除一个项目...(在另一个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)
Run Code Online (Sandbox Code Playgroud)
点是,我的print语句返回对象id(x),所以我知道它们是同一个对象,但它们不应该是,我在该集合上丢弃它new_animals.
任何洞察为什么这不排除该项目?
set.discard()从集合中删除一个项目,但您传入整个集合对象.
您需要删除元素本身,而不是内部元素的另一个集合:
self.new_animals.discard(animal)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> someset = {1, 2, 3}
>>> someset.discard({1})
>>> someset.discard(2)
>>> someset
set([1, 3])
Run Code Online (Sandbox Code Playgroud)
注意如何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)
Run Code Online (Sandbox Code Playgroud)
(我假设这.pos是两个值的元组,你可以在这里测试直接相等).
你并不需要存储new_animals在self所有的时间; 使用本地名称就足够了,这里甚至不需要.