在列表中找到元素“left”

时间:2016-02-02 23:45:37

标签: python list

我有列表list1 = ["Hello", "Goodbye", "Ohai"]

我有另一个列表,list2 = ["Hello", "Goodbye"]

我想在list1中获取剩余的项目,在这种情况下,这将是"Ohai"

4 个答案:

答案 0 :(得分:3)

>>> list1 = ["Hello", "Goodbye", "Ohai"]
>>> list2 = ["Hello", "Goodbye"]
>>> set(list1) ^ set(list2)
set(['Ohai'])

如果您只应使用列表,则可以迭代:

>>> [item for item in list1 if item not in list2]
['Ohai']

但是为什么当你有套装时呢? - )

答案 1 :(得分:1)

这需要Python set

set1 = set(list1)
set2 = set(list2)
remainder_of_exclusion = set1-set2 # think like normal sets in math, set1\set2

答案 2 :(得分:0)

如果它不在两个列表中,则会循环显示list1list2并获得x

result = [x for x in (list1 + list2) if not (x in list1 and x in list2)]

答案 3 :(得分:0)

>>> list1[len(list2):]
['Ohai']