【问题标题】:Check if n members of a list are in another list in python检查列表的n个成员是否在python的另一个列表中
【发布时间】:2014-07-17 11:22:06
【问题描述】:

想象一下,在 python 中,我们有一个列表,如下所示:

[100,111,223,456,789,880]

还有另一个列表,像这样:

[100,789,223,556,998,332,989,987]

假设两个列表中的任何一个成员都没有重复,那么在 python 中考虑第一个列表的 2 个(或 n 个)成员驻留在第二个列表中的最快方法是什么?

【问题讨论】:

  • 如果第一个列表是[100,100,100,100]怎么办?是否会认为它的 4 个元素位于第二个列表中?
  • 对于我的具体问题,我们可以假设第一个或第二个列表中的任何成员都不会重复。
  • @user2592835 - 当您将列表转换为集合时,列表中的所有重复/重复项都将被删除。

标签: python list indexing


【解决方案1】:
a=[100,111,223,456,789,880]
b=[100,789,223,556,998,332,989,987]

print list(set(a) & set(b))

#output [100, 789, 223]

【讨论】:

    【解决方案2】:

    您可以尝试使用set 及其intersection() 方法:

    L1 = [100, 111, 223, 456, 789, 880]
    L2 = [100, 789, 223, 556, 998, 332, 989, 987]    
    
    n = ...
    print len(set(L2).intersection(L1)) > n
    # True or False
    

    如果你想得到相交元素,你可以打印intersection()的结果:

    print set(L2).intersection(L1)
    # set([100, 789, 223])  # list(...) to convert to list
    

    【讨论】:

      猜你喜欢
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2021-01-04
      • 2013-11-05
      • 2012-10-08
      相关资源
      最近更新 更多