2015-06-24 59 views
0
list1 = [1, 3, 5, 7] 
list2 = [[1, "name1", "sys1"], [2, "name2", "sys2"], [3, "name3", "sys3"], [4, "name4", "sys4"]] 

我有以下2個列表,我希望能夠從列表2中檢索列表1中匹配的每個項目。Python - 列表與嵌套列表的交集

因此,其結果必然是這樣的:

result = [[1, "name1", "sys1"], [3, "name3", "sys3"]] 

另外有也是要找出不匹配的項目一個簡單的方法,

notmatch = [5, 7] 

我已閱讀本Find intersection of two lists?但它不會產生我需要的結果。

回答

1
>>> ids = set(list1) 
>>> result = [x for x in list2 if x[0] in ids] 
>>> result 
[[1, 'name1', 'sys1'], [3, 'name3', 'sys3']] 

>>> ids - set(x[0] for x in result) 
{5, 7} 
0
In [3]: result=[i for i in list2 if i[0] in list1] 
Out[4]: [[1, 'name1', 'sys1'], [3, 'name3', 'sys3']] 

In [5]: nums=[elem[0] for elem in result] 
In [6]: [i for i in list1 if i not in nums] 
Out[6]: [5, 7] 
0

使用用於查找索引的set:這將有更快的查找時間:

>>> indices = set(list1) 

選配項:

>>> matching = [x for x in list2 if x[0] in indices] 
>>> matching 
[[1, 'name1', 'sys1'], [3, 'name3', 'sys3']] 

不匹配的項目:

>>> nonmatching = [x for x in list2 if x[0] not in indices] 
>>> nonmatching 
[[2, 'name2', 'sys2'], [4, 'name4', 'sys4']] 
0
list1 = [1, 3, 5, 7] 
list2 = [[1, "name1", "sys1"], [2, "name2", "sys2"], [3, "name3", "sys3"], [4, "name4", "sys4"]] 
result = [] 

for elem in list1: 
    for x in range(len(list2)): 
     if elem == list2[x][0]: 
      result.append(list2[x]) 
print(result)