我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
当前回答
获取在temp1中而不在temp2中的元素 (假设每个列表中的元素是唯一的):
In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']
注意它是不对称的 :
In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1])
这里您可能期望/希望它等于set([1,3])。如果你想要set([1,3])作为你的答案,你可以使用set([1,2])。symmetric_difference(设置([2、3]))。
其他回答
我更喜欢使用转换到集,然后使用“差分()”函数。完整的代码是:
temp1 = ['One', 'Two', 'Three', 'Four' ]
temp2 = ['One', 'Two']
set1 = set(temp1)
set2 = set(temp2)
set3 = set1.difference(set2)
temp3 = list(set3)
print(temp3)
输出:
>>>print(temp3)
['Three', 'Four']
这是最容易理解的,而且在将来,如果你处理大型数据,将其转换为集合将删除不需要的重复项。希望能有所帮助;-)
def diffList(list1, list2): # returns the difference between two lists.
if len(list1) > len(list2):
return (list(set(list1) - set(list2)))
else:
return (list(set(list2) - set(list1)))
例如,如果list1 =[10, 15, 20, 25, 30, 35, 40]和list2 =[25, 40, 35],那么返回的列表将输出= [10,20,30,15]
由于目前的解决方案都不产生一个元组,我将抛出:
temp3 = tuple(set(temp1) - set(temp2))
另外:
#edited using @Mark Byers idea. If you accept this one as answer, just accept his instead.
temp3 = tuple(x for x in temp1 if x not in set(temp2))
像其他在这个方向上得到答案的非元组一样,它保持了顺序
这里有一个简单的方法来区分两个列表(无论内容是什么),你可以得到如下所示的结果:
>>> from sets import Set
>>>
>>> l1 = ['xvda', False, 'xvdbb', 12, 'xvdbc']
>>> l2 = ['xvda', 'xvdbb', 'xvdbc', 'xvdbd', None]
>>>
>>> Set(l1).symmetric_difference(Set(l2))
Set([False, 'xvdbd', None, 12])
希望这对你有所帮助。
如果列表是对象而不是基本类型,这是一种方法。
代码更加明确,并给出了一个副本。 这可能不是一个有效的实现,但对于较小的对象列表来说是干净的。
a = [
{'id1': 1, 'id2': 'A'},
{'id1': 1, 'id2': 'B'},
{'id1': 1, 'id2': 'C'}, # out
{'id1': 2, 'id2': 'A'},
{'id1': 2, 'id2': 'B'}, # out
]
b = [
{'id1': 1, 'id2': 'A'},
{'id1': 1, 'id2': 'B'},
{'id1': 2, 'id2': 'A'},
]
def difference(a, b):
for x in a:
for y in b:
if x['id1'] == y['id1'] and x['id2'] == y['id2']:
x['is_removed'] = True
c = [x for x in a if not x.get('is_removed', False)]
return c
print(difference(a, b))