Python - 具有嵌套列表

时间:2015-06-24 15:49:58

标签: python

list1 = [1, 3, 5, 7]
list2 = [[1, "name1", "sys1"], [2, "name2", "sys2"], [3, "name3", "sys3"], [4, "name4", "sys4"]]

我有以下2个列表,我希望能够从list2中检索list1中匹配的每个项目。

所以,结果就像:

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

另外还有一种简单的方法可以找出不匹配的项目,

notmatch = [5, 7]

我已阅读此Find intersection of two lists?,但它不会产生我需要的结果。

4 个答案:

答案 0 :(得分: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}

答案 1 :(得分: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]

答案 2 :(得分: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']]

答案 3 :(得分: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)