【Python】要过滤掉两个list,两个list相减:Error: TypeError: unsupported operand type(s) for -: ‘list‘ and ‘list‘

 1.问题

list1 = [2, 4]
list2 = [1, 2, 3, 4, 5]
list3 = list2-list1
print(list3)

要过滤掉在 list2 且在 list1 中的元素,如果直接 list2-list1,会报错: 

Traceback (most recent call last):
  File "E:/python_project/test.py", line 3, in <module>
    list3 = list2-list1
TypeError: unsupported operand type(s) for -: 'list' and 'list'

 

2.原因

python不支持像直接两个字符串相加 list1+list2 那样直接相减。

3.正确写法

[i for i in list2 if i not in list1]
list1 = [2, 4]
list2 = [1, 2, 3, 4, 5]
list3 = [i for i in list2 if i not in list1]
print(list3)