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

查看:37
本文介绍了如何检查列表中的所有项目是否都在另一个列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表说

List1 = ['a','c','c']List2 = ['x','b','a','x','c','y','c']

现在我想知道 List1 的所有元素是否都在 List2 中.在这种情况下,都有.我不能使用子集函数,因为我可以在列表中有重复的元素.我可以使用 for 循环来计算 List1 中每个项目的出现次数,并查看它是否小于或等于 List2 中的出现次数.有没有更好的方法来做到这一点?

谢谢.

解决方案

当出现次数无关紧要时,您仍然可以通过动态创建集合来使用子集功能:

<预><代码>>>>list1 = ['a', 'c', 'c']>>>list2 = ['x', 'b', 'a', 'x', 'c', 'y', 'c']>>>设置(列表1). issubset(列表2)真的

如果您需要检查每个元素在第二个列表中出现的次数是否至少与第一个列表中的相同,您可以使用 Counter 类型并定义您自己的子集关系:

<预><代码>>>>从集合导入计数器>>>def counterSubset(list1, list2):c1,c2 = 计数器(列表 1),计数器(列表 2)对于 c1.items() 中的 k, n:如果 n >c2[k]:返回错误返回真>>>计数器子集(列表1,列表2)真的>>>counterSubset(list1 + ['a'], list2)错误的>>>counterSubset(list1 + ['z'], list2)错误的

如果您已经有计数器(无论如何这可能是存储数据的有用替代方案),您也可以将其写为一行:

<预><代码>>>>all(n <= c2[k] for k, n in c1.items())真的

I have two lists say

List1 = ['a','c','c']
List2 = ['x','b','a','x','c','y','c']

Now I want to find out if all elements of List1 are there in List2. In this case all there are. I can't use the subset function because I can have repeated elements in lists. I can use a for loop to count the number of occurrences of each item in List1 and see if it is less than or equal to the number of occurrences in List2. Is there a better way to do this?

Thanks.

解决方案

When number of occurrences doesn't matter, you can still use the subset functionality, by creating a set on the fly:

>>> list1 = ['a', 'c', 'c']
>>> list2 = ['x', 'b', 'a', 'x', 'c', 'y', 'c']
>>> set(list1).issubset(list2)
True

If you need to check if each element shows up at least as many times in the second list as in the first list, you can make use of the Counter type and define your own subset relation:

>>> from collections import Counter
>>> def counterSubset(list1, list2):
        c1, c2 = Counter(list1), Counter(list2)
        for k, n in c1.items():
            if n > c2[k]:
                return False
        return True
   
>>> counterSubset(list1, list2)
True
>>> counterSubset(list1 + ['a'], list2)
False
>>> counterSubset(list1 + ['z'], list2)
False

If you already have counters (which might be a useful alternative to store your data anyway), you can also just write this as a single line:

>>> all(n <= c2[k] for k, n in c1.items())
True

这篇关于如何检查列表中的所有项目是否都在另一个列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆