如何从一个列表中删除未包含在另一个列表中的元素?

时间:2017-01-06 13:05:01

标签: python python-2.7

我有两个列表列表:

arr1 = [[1,2,3],
        [2,5,1,1],
        [3,1,1]]

arr2 = [[2,3,6,1],
        [8,1,3],
        [5,5,6]]

我需要检查arr2中哪些元素不包含在arr1中,并从arr2中删除这些元素。

结果必须是:

arr2 = [[2,3,1],
        [1,3],
        [5,5]]

6和8不包含在arr1中,因此在arr2中删除。

怎么做?

1 个答案:

答案 0 :(得分:1)

var iq = $iq({type: 'get', to: 'some host'}).c('query', {xmlns: 'jabber:iq:conversations'}); connection.sendIQ(iq);

输出:

arr1 = [[1, 2, 3],
        [2, 5, 1, 1],
        [3, 1, 1]]

arr2 = [[2, 3, 6, 1],
        [8, 1, 3],
        [7, 5, 6]]

set1 = set(sum(arr1, []))
print('Elements found in arr1:')
print(set1)

arr3 = [[x for x in sub if x in set1]
        for sub in arr2]

print('Sublists of arr3:')
for sub in arr3:
    print(sub)