检查列表与列表理解重叠

Check list overlap with list comprehensions

我在 python 中有一个脚本生成 2 个不同大小的随机列表和 return 第三个列表只包含两个列表之间共有的元素 (没有重复项) 使用列表推导

示例:

a = [3, 8, 9, 6, 5, 3, 7, 8, 2, 10]
b = [7, 13, 20, 12, 12, 2, 6, 1, 2, 8, 19, 3, 15, 16, 14, 22, 22, 4, 9, 15, 8, 13]

我的结果列表是

c = [7, 2, 6, 2, 8, 3, 9, 8]

不过应该是

c = [7, 6, 2, 8, 3, 9]

这是我所做的:

c = [i for i in max(a, b) if i in min(a, b) and i not in c]

提前致谢!

您可以通过以下方式使用集合:

c = list(set(a).intersection(set(b)))

这会给你:

[2, 3, 6, 7, 8, 9]

之所以有效,是因为 set 项是无序的、不可更改的,并且不允许重复值。将其与 intersection 方法结合使用,您将获得结果。

使用sets, not list comprehensions:

c = list(set(a) & set(b))
print(c)
# [2, 3, 6, 7, 8, 9]

来自docs

A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

    a = [3, 8, 9, 6, 5, 3, 7, 8, 2, 10]
    b = [7, 13, 20, 12, 12, 2, 6, 1, 2, 8, 19, 3, 15, 16, 14, 22, 22, 4, 9, 15, 8, 13]
    c=[]
    for i in max(a,b):
        if i in min(a, b) and i not in c:
            c.append(i) 
    print(c)