【问题标题】:How can I take two lists and return the intersection of the sets in Python?如何获取两个列表并返回 Python 中集合的交集?
【发布时间】:2017-10-05 15:41:40
【问题描述】:

如何在 python 中找到两个列表的交集?我已经用 in 操作符试过了,但我不确定如果没有我该怎么做。

a = [2, 4, 6, 8, 10]
b = [4, 8, 12, 16, 20]
set(a) & set(b)

这应该返回 [4, 8]

【问题讨论】:

  • 使用算子有什么问题?
  • "我知道怎么做 X,但是如果不使用 旨在做 X 的功能,我怎么能做到呢?"

标签: python-3.x list set-intersection


【解决方案1】:

您可以将列表转换为集合,然后致电intersection。 Python Set 具有 intersection 作为内置方法。

s1 = set(a)
s2 = set(b)
a.intersection(b)
# set([4,8])

【讨论】:

    【解决方案2】:

    所以你可以使用下面的例子得到你的交叉点。

    intersection已经是set的一等部分,可以直接使用

    a = [2, 4, 6, 8, 10]
    b = [4, 8, 12, 16, 20]
    set(a).intersection(b)
    

    sets 模块提供了用于构造和操作独特元素的无序集合的类。计算集合上的标准数学运算,例如交集、联合等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      相关资源
      最近更新 更多