简体   繁体   English

如果 B 的任何子列表在 A 中,如何比较列表 A 和 B 并返回是

[英]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]] .假设有两个列表A=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]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 .我想比较这两个列表,如果 B 的任何子列表在 A 中,则返回yes ,如果不返回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] .另外,我想要 B 的第二个子列表[5,6,4]返回yes ,因为它具有 A 的第二个子列表的所有项目,即[4,5,6]

Therefore, output should be like below:因此,output 应如下所示:

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:您可以在同一循环中对一个 go 中的数据 A 和数据 B 进行排序:

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. c用作计数器,仅实现单张打印。 You can do it maybe in a fancier way using break , however, we might need the help of someone more experienced than I am.您可以使用break以一种更好的方式来完成它,但是,我们可能需要比我更有经验的人的帮助。

To make it work, for each element in B and in A we sort it right after its extraction from the list.为了使它工作,对于BA中的每个元素,我们在从列表中提取它之后立即对其进行排序。 Then we compare them.然后我们比较它们。

c is included in the first loop, so we can reset it on every entry. c包含在第一个循环中,因此我们可以在每个条目上重置它。

The printing has to be made after finishing the second loop but surely, before entering the first loop again.必须在完成second loop后进行printing ,但必须在再次进入第一个循环之前进行。

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 :如果子列表仅包含唯一值,您可以将B中的值转换为集合,并将它们与从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: Output:

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

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

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