[英]Compare two list, and create other two lists with intersection and difference
我有2个列表A和B。
在B列表中,我可以包含列表A中的多个元素。
例如:
A = [1,3,5,7, 9, 12, 14]
B = [1,2,3,3,7,9,7,3,14,14,1,3,2,5,5]
我要创建:
我的方法是两个循环:
l1 = []
l2 = []
for i in A:
for j in B:
if i == j
l1.append[i]
...
l1 = set(l1)
我不知道这是否是一个好方法,再加上2)点(b中没有什么)。
而且我不能else on i!=j
使用else on i!=j
,因为重复并且B中没有顺序。
#to create a list with ids that are in A and found in B (unique)
resultlist=list(set(A)&set(B))
print(list(set(A)&set(B)))
#to create a list of ids that are in A and have no corresponding in B (unique)
print(list(set(A)-set(B)))
#the numbers in B, that don't have a corespondent in A
print(list(set(B)-set(A)))
将列表转换为set
,然后执行设置操作
>>> set_A = set(A)
>>> set_B = set(B)
>>> list(set_A & set_B)
[1, 3, 5, 7, 9, 14] # set intersection
>>> list(set_A - set_B) # set difference
[12]
>>> list(set_B - set_A)
[2]
使用python,您可以简单地使用set类型:
list(set(A) & set(B))
将返回一个包含列表A
和B
之间的元素交集的列表。
list(set(A) - set(B))
将返回一个列表,其中包含A
中的所有元素,而不是B
中的所有元素。
反之亦然:
list(set(B) - set(A))
将返回一个列表,其中包含B
而不是A
中的所有元素。
使用集合操作 :
A = [1, 3, 5, 7, 9, 12, 14]
B = [1, 2, 3, 3, 7, 9, 7, 3, 14, 14, 1, 3, 2, 5, 5]
sa = set(A)
sb = set(B)
# intersection
l1 = list(sa & sb)
# [1, 2, 3, 5, 7, 9, 12, 14]
# differences
l2 = list(sa - sb)
# [12]
l3 = list(sb - sa)
# [2]
您可以使用“ a in L”功能,如果元素在列表中,该功能将返回True。 例如
A = [1,3,5,7, 9, 12, 14]
B = [1,2,3,3,7,9,7,3,14,14,1,3,2,5,5]
common = []
uncommon = []
for a in A:
if a in B:
common.append(a)
else:
uncommon.append(a)
print(common)
print(uncommon)
这应该给您一个很好的提示,说明如何解决另一个问题。 最好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.