python - 复制一组并排除一个项目

标签 python set

我正在尝试基于另一组创建一组,并且只排除一个项目... (使用集合内的对象在另一个 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/

相关文章:

python - 如何在 Tkinter TkTable 中插入/设置数据

python - 为什么 pandas 在我的直方图中插入空格?

python - 如何在 py_function 之后 reshape (图像,标签)数据集

set - 从一组 2D 点创建三角形表面

java - 字符串列表的高效交集和并集

algorithm - 暴力破解数字的简单方法

python - Matplotlib Boxplot 和 pandas 数据框数据类型

Python:如果集合中没有负计数器部分,则删除集合中的数字

java - 当两个元素相同时合并集合

python - 直接在HDFS中生成文件