【问题标题】:Pythonic way subtract list left duplicate elements [duplicate]Pythonic方式减去列表左侧重复元素[重复]
【发布时间】:2017-03-09 11:09:52
【问题描述】:

我想减去两个列表并阅读这个问题Remove all the elements that occur in one list from another

# a-b
def subb(a,b):
    return [i for i in a if i not in b]

print subb([1,2,1,2],[1,2])

但结果是空列表,这不是我想要的,我认为应该是[1,2],所以我更改了我的代码:

def subb(a,b):
    for i in b:
        if i in a:
            a.remove(i)
    return a

现在我想要一个 Pythonic 的方式来用一个简单的表达式替换这个函数,这样我就可以很容易地在函数中使用结果。这可能吗?

谢谢。

【问题讨论】:

  • 那么问题是subb 具有破坏性?

标签: python list


【解决方案1】:

如果我没有误解你的意思,这就是你想要的:

x, y = [1,2,1,2], [1,2]

print [j for j in x if not j in y or y.remove(j)]

输出:

[1, 2]

如果你想让y的值保持不变,你可以尝试使用deepcopy

from copy import deepcopy
yy = deepcopy(y)
print [j for j in x if not j in yy or yy.remove(j)]

【讨论】:

  • 这很漂亮!
  • 但这对y@Mike具有破坏性
  • 是的,我只需要结果。
猜你喜欢
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
  • 2014-04-20
  • 1970-01-01
  • 2022-01-09
  • 2020-03-19
  • 2017-09-12
  • 1970-01-01
相关资源
最近更新 更多