【问题标题】:Python - eliminating common elements from two listsPython - 从两个列表中消除常见元素
【发布时间】:2015-06-05 23:20:57
【问题描述】:

如果我有两个列表:

a = [1,2,1,2,4] and b = [1,2,4]

如何获得

a - b = [1,2,4]

如果 a 中存在一个元素,则 b 中的一个元素仅从 a 中删除一个元素。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您可以使用itertools.zip_longest 压缩不同长度的列表,然后使用列表理解:

    >>> from itertools import zip_longest
    >>> [i for i,j in izip_longest(a,b) if i!=j]
    [1, 2, 4]
    

    演示:

    >>> list(izip_longest(a,b))
    [(1, 1), (2, 2), (1, 4), (2, None), (4, None)]
    

    【讨论】:

    • 我收到以下错误 - ImportError: cannot import name 'izip_longest'
    • @hmm 对不起,你在 python 3 中你需要zip_longest fised!
    【解决方案2】:
    a = [1,2,1,2,4] 
    b = [1,2,4]
    c= set(a) & set(b)
    d=list(c)
    

    答案只是对本主题的答案稍作修改: Find non-common elements in lists

    因为你不能迭代一个集合对象: https://www.daniweb.com/software-development/python/threads/462906/typeerror-set-object-does-not-support-indexing

    【讨论】:

    • 您可以使用set(a) - set(b),但这也会删除所有重复项并打乱顺序,这可能不是有意的。
    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 2018-07-08
    • 2020-06-16
    • 1970-01-01
    • 2012-12-29
    • 2016-01-18
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多