我想用python代码以最简单的方式解决下面的问题:
a = ['one','two','three','four','five','six','seven','eight','nine']
b = ['three','seven','nine']
如何从a:
中仅删除b的元素我需要一个 - >
A=['one', 'two', 'four', 'five', 'six', 'eight']
答案 0 :(得分:3)
使用列表推导来构建新列表:
A = [elem for elem in a if elem not in b]
如果您将b
设为一个集合,则会更有效:
b = set(b)
因为成员资格测试(in
和not in
)对于集合而言比对列表要快得多,其中每个包含的项目都必须单独测试。
演示:
>>> a = ['one','two','three','four','five','six','seven','eight','nine']
>>> b = ['three','seven','nine']
>>> b = set(b)
>>> b
set(['seven', 'nine', 'three'])
>>> [elem for elem in a if elem not in b]
['one', 'two', 'four', 'five', 'six', 'eight']
答案 1 :(得分:0)
将它们转换为设置并找到差异。
>>> a = ['one','two','three','four','five','six','seven','eight','nine']
>>> b = ['three','seven','nine']
>>> print (list(set(a)-set(b))) #converted to list,since you want the output as list.
['two', 'eight', 'one', 'five', 'six', 'four']
>>>