我该怎么做?
>>> a
['eins', 'zwei', 'drei', 'vier', 'fünf']
>>> b
['eins', 'zwei', 'drei']
>>> c = a - b
这也行不通。
c = a[:].remove(b)
答案 0 :(得分:2)
如果您不需要重复元素,可以使用set
s作为jadelord说
如果列表a
包含重复的元素并且您需要它们,则应使用
c = list(filter(lambda x: x not in b, a))
或者
c = [x for x in a if x not in b]
答案 1 :(得分:1)
您正在寻找的是与python中的set
数据类型相关联的功能。不是lists
!
这可以解决您的问题:
c = list(set(a) - set(b))
答案 2 :(得分:0)
Set和ImmutableSet的实例都提供以下操作:
Operation Equivalent Result
len(s) cardinality of set s
x in s test x for membership in s
x not in s test x for non-membership in s
s.issubset(t) s <= t test whether every element in s is in t
s.issuperset(t) s >= t test whether every element in t is in s
s.union(t) s | t new set with elements from both s and t
s.intersection(t) s & t new set with elements common to s and t
s.difference(t) s - t new set with elements in s but not in t
s.symmetric_difference(t) s ^ t new set with elements in either s or t but not both
s.copy() new set with a shallow copy of s