迭代期间多组中的就地设置元素移除

时间:2014-08-13 17:01:17

标签: python map filter lambda list-comprehension

我有两组对象,s1和s2,它们的长度不同。我想根据这个伪代码就地修改这两个集:

for a1 in s1:
  for a2 in s2:
    if a1.name == a2.name:
      # insert some stuff into database
      # remove a2 from s2 and a1 from s1

s1和s2现在只有s1 [n] .name!= s2 [n] .name的元素。当然,从集合中删除项目不应影响正在进行的迭代的其余部分。

我意识到解决这个问题的方法不止一种。我正在努力想象一个" python-style"方式(即不使用嵌套for循环):map?过滤?拉姆达?列表理解?算法性能并不是特别重要,因为这些集非常小 - 每个元素不超过100个元素,但通常每个元素大约10个。

2 个答案:

答案 0 :(得分:0)

更新

我重新考虑了这一点。对于就地:

for a1 in s1:
    for a2 in s2:
        if a1.name == a2.name:
            s1.remove(a1)
            s2.remove(a1)

以及更多" python-style"方式:

s1_filtered = [r for r in s1 if r not in s2]
s2_filtered = [r for r in s2 if r not in s1]

只是做 -

for a1 in s1:
  for a2 in s2:
    if a1.name == a2.name:
        del a1 #you get an error
        del a2 #you get an error
        # insert some stuff into database
        # remove a2 from s2 and a1 from s1

答案 1 :(得分:0)

由于我没有50个代表评论代码,我会像常规答案一样写:

for a1 in s1:
  for a2 in s2:
    if a1.name == a2.name: # since a1 may have been deleted while iterating through s2 .name is essentailly called on null and thats where you get UnboundLocalError: local variable 'a1' referenced before assignment.
        del a1 #you get an error because a1 was previously deleted 
        del a2 #you get an error