使用in
运算符,您可以检查元素是否处于序列中.
>>> list2 = ['a','c','z','y'] >>> 'x' in list2 False >>> 'y' in list2 True
使用列表理解:
>>> 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']
但x in list
效率不高.你最好转换list2
成一个set
对象.
>>> set2 = set(list2) >>> [x for x in list1 if x in set2] ['a', 'a', 'c']
从Python 3开始使用 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']
该list
呼叫是必要的,因为filterfalse
返回一个itertools
对象.
您也可以使用该filter
功能
>>> list(filter(lambda x: x in list2 , list1)) ['a', 'a', 'c']