Remove elements from a 2D-list based on a 1D-list
我有两张单子
List A (called a) : 2D list like this : [[1,'aaa'],[2,'bbb'],[3,'ccc'],[4,'ddd']]
List B (called b) : 1D list like this : ['aaa','abc','cba','acb']
号
我想根据列表B的内容从列表A中删除元素。在示例中,预期结果是:
New List C (called c) : [[2,'bbb'],[3,'ccc'],[4,'ddd']] //Since there is no element 'bbb', 'ccc' or 'ddd' in the list B
号
我目前正在使用以下代码,我发现它非常慢:
1 2 3 4 | c = [] for elem in a: if elem[1] not in b: c.append(elem) |
有没有更好的方法来做这个移除?创建新的列表并附加元素还是从原始列表中删除元素更好?
谢谢你的帮助!
不太快,但使用列表理解可能更清晰
1 | c = [elem for elem in a if elem[1] not in b] |
如果
1 2 | b_set = set(b) c = [elem for elem in a if elem[1] not in b_set] |
号
如果
1 2 3 4 5 | a_dict = {k: v for v, k in a} b_set = set(b) set_difference = a_dict.keys() - b_set c = [(a_dict[k]: k) for k in set_difference] |