简体   繁体   中英

How to compare list A and B and return yes if any sublist of B is in A

Assume there are two lists A=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]] and B=[[1,2,3],[5,6,4],[7,1,9]] . I want to compare these two lists and return yes if any sub list of B is in A and if not return no . Also, I want 2nd sublist of B which is [5,6,4] returns yes since it has all items of 2nd sub list of A which is [4,5,6] .

Therefore, output should be like below:

yes
yes
no

This is the code:

A=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
B=[[1,2,3],[5,6,4],[7,1,9]] 
     
for i in range(len(B)):
    if B[i] in A:
        print('yes')
        
    else:
        print('no')

You can sort data A and data B in one go in the same loop:

A=[[1,3,2],[4,6,5],[7,8,9],[10,11,12]] #I messed up A as well
B=[[1,2,3],[5,6,4],[7,1,9]] 
     
for i in range(len(B)):
    if sorted(B[i]) in map(sorted,A):
        print('yes')
        
    else:
        print('no')
for i in B:
    i.sort()
    c=0
    for k in A:
        k.sort()
        if i==k:
           c+=1
    if c>0:
        print("yes")
    else:
        print("no")

Not too fancy, but does the job. c is used as a counter to achieve the single print only. You can do it maybe in a fancier way using break , however, we might need the help of someone more experienced than I am.

To make it work, for each element in B and in A we sort it right after its extraction from the list. Then we compare them.

c is included in the first loop, so we can reset it on every entry.

The printing has to be made after finishing the second loop but surely, before entering the first loop again.

If the sublists only contain unique values, you can convert the values in B to sets and compare them with sets derived from the values in A :

A=[[1,3,2],[5,4,6],[7,8,9],[10,11,12]]
B=[[3,1,2],[5,6,4],[7,1,9]] 

Asets = map(set, A)
print(['yes' if any(set(bsub) == asub for asub in Asets) else 'no' for bsub in B])

Output:

['yes', 'yes', 'no']

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