检查list1中是否存在list1中的所有元素python [duplicate](Check if all elements in list1 exist in list2 python [dupl

编程入门 行业动态 更新时间:2024-10-28 10:23:16
检查list1中是否存在list1中的所有元素python [duplicate](Check if all elements in list1 exist in list2 python [duplicate])

这个问题在这里已有答案:

如何检查列表中的所有项目是否都在另一个列表中? 6个答案

我希望能够找到list1中是否存在list1中的所有元素,两个列表都包含chars。 每个列表中相同元素出现的次数很重要。

我尝试使用子集但是没有注意到项目出现在列表中的次数

例如

list1 = [a, b, c] list2 = [a, b, c, b]

它会发现list2是list1的一个子集,而我只希望我的函数在以下情况下执行:

list1 = [a, b, c, b, i] list2 = [a, c, b, b]

因为这意味着list2中的所有项都出现在list1中。

如果有人感兴趣,使用计数器对于大字符串来说是低效的,所以我最终将list1的所有元素添加到字典中,其中值是每个元素的出现次数并减去list2的所有元素。 如果任何值最终为负,则list2中的所有项都不会出现在list1中

This question already has an answer here:

How to check if all items in a list are there in another list? 6 answers

I want to be able to find whether all elements in list1 exist in list2, both lists containing chars. The number of times the same element appears in each list is important.

I tried using subsets however that didn't take note of the number of times an item appeared in a list

e.g.

list1 = [a, b, c] list2 = [a, b, c, b]

It would find list2 a subset of list1, whereas I would only want my function to execute if:

list1 = [a, b, c, b, i] list2 = [a, c, b, b]

as this means all items in list2 appear in list1.

If anyone was interested, using a counter was inefficient for large strings so I ended up adding all elements of list1 to a dictionary, with the values being number of occurances of each element and subtracted all elements of list2. If any values ended up negative not all items in list2 appear in list1

最满意答案

您可以使用collections.Counter计算两个列表中的项目,并检查第一个列表中相应项目的计数是否> =第二个列表中的计数:

>>> from collections import Counter >>> c = Counter("abcbi") >>> d = Counter("acbb") >>> c.subtract(d) >>> if all(v >= 0 for k, v in c.items()): ... print("All items exist") ... All items exist

You could count the items in both lists with collections.Counter and check that the counts for the corresponding items in the first list are >= than those in the second:

>>> from collections import Counter >>> c = Counter("abcbi") >>> d = Counter("acbb") >>> c.subtract(d) >>> if all(v >= 0 for k, v in c.items()): ... print("All items exist") ... All items exist

更多推荐

本文发布于:2023-07-22 03:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1216697.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是否存在   元素   python   duplicate   exist

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!