how to keep elements of a list based on another list

前端 未结 3 1725
小鲜肉
小鲜肉 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

    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']
    

提交回复
热议问题