简体   繁体   中英

Compare two list, and create other two lists with intersection and difference

I have 2 lists A and B.

In the B list I can have multiple elements from list 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)
  2. to create a list of ids that are in A and have no corresponding in B (unique)
  3. Nice to get also: the numbers in B, that don't have a corespondent in A

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).

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

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

will return a list containing the element intersection between lists A and B .

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

Will return a list containing all the elements that are in A and not in B .

Vice versa:

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

Will return a list containing all the elements that are in B and not in 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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