2017-04-16 42 views
-6

我与他们不同的字符串比如Python列表:在Python中搜索列表以查找匹配项?

List1 = ["a","b","c","d"] 
List2 = ["b","d","e","f"] 
List3 = [] 
List4 = ["d","f","g"] 

我需要通过这些名单迭代,只要它们不为空,并认为,在所有非空列表中的项目。在上面的例子中,完全匹配列表将是[“d”],因为这是唯一出现在所有非空列表中的项目。 List3是空白的,所以它不在列表中并不重要。

+0

输出列表的顺序是否重要? – timgeb

+1

你“需要一个代码”? –

+0

不,它不。只要我可以追加每个完全匹配。 – Yasir

回答

0
for thing in list1: # iterate each item, you can check before hand if its not empty 
     if len(list2) > 0: # if not empty 
     if thing in list2: # in the list 
      # do the same thing for the other lists 

类似的东西

+1

'if len(list2)> 0:#if not empty'。 '如果list2:'会检查它不是一个空列表(这是错误的)。 – roganjosh

+0

@roganjosh好点 – LLL

4

这里的一些函数式编程之美:

from operator import and_ 
from functools import reduce 

Lists = List1, List2, List3, List4 

result = reduce(and_, map(set, filter(None, Lists))) 
+3

这有点酷。 – timgeb

+0

btw,'operator'-free version:'reduce(set.intersection,map(set,filter(None,Lists)))' – timgeb

+0

@timgeb,很酷,这样会更好看。另外,减少进口。 – ForceBru

0

我现在不能测试此权利,但类似下面应该工作:

intersection(set(l) for l in [List1, List2, List3, List4] if l) 

它使用Python内建的set数据类型来做交点歌剧灰。

+0

'intersection'是'set'的一种方法,而不是一个独立的函数。 – ForceBru