代码之家  ›  专栏  ›  技术社区  ›  PanDe

在两个列表中查找公共元素

  •  -2
  • PanDe  · 技术社区  · 6 年前

    我有两个清单:

    list_1 = ['rwww corp\pan 2323 2018-23-23 0% c:\program files\pa.txt', 'rwww corp\pand 2323 2018-23-23 0% c:\program files\monkey.txt']
    
    list_2 = ['c:\program files\pa.txt']
    

    我想知道list_1中是否有list_2元素,如果有,请打印出来。

    在这种情况下,ListSy2元素在ListHy1的索引0中,如何使用一个内衬来实现这一点?

    我用两个for循环来完成这项工作很无聊:

    for e in list_1:
        for k in list_2:
              if k in e:
                   print e
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   spejsy    6 年前

    这相当于使用列表理解的循环:

    [print e for e in list_1 for k in list_2 if k in e]
    
        2
  •  1
  •   AChampion    6 年前

    首先我会调查 itertools.product() 然后我就不会用列表来理解副作用,例如:

    import itertools as it
    
    print '\n'.join(e for e, k in it.product(list_1, list_2) if k in e)
    

    我也会考虑 __future__ 使用 print_function 例如:

    from __future__ import print_function
    import itertools as it
    
    print('\n'.join(e for e, k in it.product(list_1, list_2) if k in e))
    
        3
  •  0
  •   hygull    6 年前

    @ Petpan ,你可以使用 list comprehension 满足你的需要。

    你不应该用列表理解的方法。

    在线试用 http://rextester.com/QBQDO38144 .

    list_1 = ['rwww corp\pan 2323 2018-23-23 0% c:\program files\pa.txt', 
              'rwww corp\pand 2323 2018-23-23 0% c:\program files\monkey.txt', 
              'c:\program files\pa.txt',
              'c:\program files\pex2.txt',
              'c:\program files\pex5.txt',
              'c:\program files\pex4.txt',
              ]
    
    list_2 = ['c:\program files\pa.txt', 'c:\program files\pex2.txt', 'c:\program files\pex3.txt',]
    
    # You should not use list comprehension for this purpose
    # It will print items in list_1 if it also exists in list_2
    [print(e, 'exists in list_1') for e in list_2 if e in list_1]
    

    产量

    c:\program files\pa.txt exists in list_1
    c:\program files\pex2.txt exists in list_1