python - 两个可迭代对象的条件连接

标签 python set iterable

我遇到了一个奇怪的情况,导致我感到困惑(和错误)。我已将变量重命名为更清晰,但问题是真实的。我有两个需要合并的迭代。组合应该是连词,​​不能重复。但是,如果一个元素与另一个元素“相反”,则两个元素都不应该存在于最终集合中。

概念示例:(a, b, c) COMBINE (b, c', d) -> (a, b, d) # 让 c 与 c' 相反

这是我当前的实现,部分失败是因为我试图在迭代集合时修改集合的大小:

# atom_list and atom_set are distinct not only in their type but also their contents.
for atom in atom_list:
    should_add = True
    for other_atom in atom_set:
        if atom.is_opposite(other_atom):
            # Todo: cause anti-matter/matter explosion!!
            atom_set.remove(other_atom)
            should_add = False
    if should_add:
        atom_set.add(atom)

对于如何使这个更干净(并且在不修改我正在迭代的集合的情况下工作)有什么想法吗?我觉得这个问题的一个好的解决方案不仅仅是首先复制集合......

最佳答案

正如您所说,在迭代可迭代对象时修改它不是一个好主意。为什么不创建另一组?

combined_set = set()
for atom in atom_list:
    if atom.opposite() not in atom_set:
        combined_set.add(atom)

atom_list_set = set(atom_list)
for atom in atom_set:
    if atom not in atom_list_set:
        combined_set.add(atom)

这假设存在一个 opposite() 方法,该方法返回原子的相反值。第二个for循环处理atom_set中但不在atom_list中的原子。

关于python - 两个可迭代对象的条件连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27132347/

相关文章:

带有命名空间的 Python xml 解析器

python - 如何保养一套套?

java - 我可以简化这个吗? (字节中 1 位的异或)

python - 将 Pandas 中的列索引重置为 0,1,2,3 ...?

python - 州缩写的正则表达式(python)

python - 如何解决clang的Python绑定(bind)加载错误?

c++ - std::set 中打印的垃圾值

java:分页结果的设计模式

python - 找到回文python空间复杂度?

java - Java中LinkedList类的iterator()方法在哪里?