简体   繁体   English

检查列表列表的所有元素是否在另一个列表列表Python中

[英]Checking if all elements of a List of Lists are in another List of Lists Python

My question is, how do you check if all of the elements of a list of lists are in another list of lists? 我的问题是,您如何检查列表列表的所有元素是否在另一个列表列表中? Or maybe better phrased, how do you check if one list of lists is a subset of another list of lists? 或许用更好的措辞来说,如何检查一个列表列表是否是另一个列表列表的子集? The answer posted below only works if you have a list of, say, strings but the answer does not work for my situation. 仅当您具有字符串列表时,以下发布的答案才有用,但该答案不适用于我的情况。

How to check if all items in a list are there in another list? 如何检查一个列表中的所有项目是否在另一个列表中?

Something I have tried is something like this: 我尝试过的东西是这样的:

if all(item in list1 for item in list2): 

which does not work. 这不起作用。

Convert your sublists to tuples, for example: 将您的子列表转换为元组,例如:

In [2]: a = [[2,3],[5,6],[8,9]]

In [3]: b = [[2,3],[5,6],[8,9], [10,11]]

In [4]: set(tuple(x) for x in a).issubset(tuple(x) for x in b)
Out[4]: True

This is really really easy if you just even tried to see what that piece of code gave you... 如果您甚至只是想看看那段代码给了您什么,这真的很容易。

>>> l1 = [1,2]
>>> l2 = [1,2,3,4,5]
>>> all(l1)
True
>>> [item in l1 for item in l2]
[True, True, False, False, False]
>>> help(all)
Help on built-in function all in module builtins:

all(...)
    all(iterable) -> bool

    Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.

Anyhow you need to turn them into sets and compute the issubset method 无论如何,您都需要将它们变成集合并计算issubset方法

>>> s1 = set(l1)
>>> s2 = set(l2)
>>> s1.issubset(s2)
True

Edit yes, as others have noted this only works if all the elements of the list are unique and you're not looking for a set math but for an exact match since sets are by default a collection of unique objects. 编辑是的,就像其他人指出的那样,这仅在列表的所有元素都是唯一的并且您不是在寻找数学集合而是完全匹配的情况下才有效,因为集合默认是唯一对象的集合。

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

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