简体   繁体   English

比较两个列表,并创建具有交集和差的其他两个列表

[英]Compare two list, and create other two lists with intersection and difference

I have 2 lists A and B. 我有2个列表A和B。

In the B list I can have multiple elements from list A. 在B列表中,我可以包含列表A中的多个元素。

For example: 例如:

A = [1,3,5,7, 9, 12, 14]
B = [1,2,3,3,7,9,7,3,14,14,1,3,2,5,5]

I want to create: 我要创建:

  1. to create a list with ids that are in A and found in B (unique) 创建一个具有在A中且在B中找到的ID的列表(唯一)
  2. to create a list of ids that are in A and have no corresponding in B (unique) 创建一个在A中但在B中没有对应ID的ID列表(唯一)
  3. Nice to get also: the numbers in B, that don't have a corespondent in A 也很高兴:B中没有数字的数字

My approach is two loops: 我的方法是两个循环:

l1 = []   
l2 = []
for i in A:
    for j in B:
      if i == j
       l1.append[i]
...
l1 = set(l1)

I don't know if this is a good approach, plus remains the 2) point(what is not in b). 我不知道这是否是一个好方法,再加上2)点(b中没有什么)。

And I can't use else on i!=j , because of repetitions and no order in 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)))

Convert the list to set and then perform set operations 将列表转换为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]

With python you can simply use the set type: 使用python,您可以简单地使用set类型:

list(set(A) & set(B))

will return a list containing the element intersection between lists A and B . 将返回一个包含列表AB之间的元素交集的列表。

list(set(A) - set(B))

Will return a list containing all the elements that are in A and not in B . 将返回一个列表,其中包含A中的所有元素,而不是B中的所有元素。

Vice versa: 反之亦然:

list(set(B) - set(A))

Will return a list containing all the elements that are in B and not in A . 将返回一个列表,其中包含B而不是A中的所有元素。

Use set operations : 使用集合操作

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]

you could use the 'a in L' functionality, which will return True if an element is in a List. 您可以使用“ a in L”功能,如果元素在列表中,该功能将返回True。 eg 例如

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)

this should give you a good hint on how to approach the other question. 这应该给您一个很好的提示,说明如何解决另一个问题。 best 最好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM