这个问题在这里已有答案:
如何检查列表中的所有项目是否都在另一个列表中? 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 answersI 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 existYou 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更多推荐
发布评论