两个Iterables的条件连接

2024-04-18 06:16:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个奇怪的情况,这是造成我混乱(和错误)我已经重新命名的变量,以更清楚,但问题是真实的。我需要合并两个iterables。这个组合应该是连词,不能重复。但是,如果一个元素是另一个元素的“对立面”,那么两个元素都不应该存在于最终的集合中。你知道吗

概念示例:(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)

对于如何使这个更干净(并且在不修改我正在迭代的集合的情况下工作)有什么想法吗?我觉得解决这个问题的好办法不仅仅是一开始就抄袭片子。。。你知道吗


Tags: inadd元素forif错误情况list
2条回答

快速“肮脏”解决方案:

s1 = set([1, 2, 3])
s2 = set([4, -2, 5])
res = [x for x in s1 | s2 if -x not in s1 and -x not in s2]

2和-2是我们排除的相反元素。它给出了[1, 3, 4, 5]。你知道吗

正如您所说的,在迭代时修改iterable不是一个好主意。为什么不创建另一个集合?你知道吗

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\u集中但不在atom\u列表中的原子。你知道吗

相关问题 更多 >