how to keep elements of a list based on another list

前端 未结 3 1710
小鲜肉
小鲜肉 2020-12-03 16:38

I have two lists looking like:

list1 = [\'a\',\'a\',\'b\',\'b\',\'b\',\'c\',\'d\',\'e\',\'e\',\'g\',\'g\']

list2 = [\'a\',\'c\',\'z\',\'y\']
相关标签:
3条回答
  • 2020-12-03 17:12

    Using in operator, you can check whether an element is in a seqeunce.

    >>> list2 = ['a','c','z','y']
    >>> 'x' in list2
    False
    >>> 'y' in list2
    True
    

    Using list comprehension:

    >>> list1 = ['a','a','b','b','b','c','d','e','e','g','g']
    >>> list2 = ['a','c','z','y']
    >>> [x for x in list1 if x in list2]
    ['a', 'a', 'c']
    

    But x in list is not efficient. You'd better convert list2 to a set object.

    >>> set2 = set(list2)
    >>> [x for x in list1 if x in set2]
    ['a', 'a', 'c']
    
    0 讨论(0)
  • 2020-12-03 17:12

    From Python 3 onwards use itertools.filterfalse

    >>> import itertools
    >>> list1 = ['a','a','b','b','b','c','d','e','e','g','g']
    >>> list2 = ['a','c','z','y']
    >>> list(itertools.filterfalse(lambda x:x not in list2,list1))
    ['a', 'a', 'c']
    

    The list call is necessary as filterfalse returns an itertools object.

    You can also use the filter function

    >>> list(filter(lambda x: x in list2 , list1))
    ['a', 'a', 'c']
    
    0 讨论(0)
  • 2020-12-03 17:15

    One alternative approach with numpy:

    import numpy as np
    
    np.asarray(list1)[np.in1d(list1, list2)].tolist()
    #['a', 'a', 'c']
    
    0 讨论(0)
提交回复
热议问题