检查list1中是否存在list1中的所有元素

时间:2016-03-10 08:51:48

标签: python list python-3.x subset

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

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

e.g。

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

5 个答案:

答案 0 :(得分:4)

您可以使用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

答案 1 :(得分:1)

您可以使用collections.Counter

 if(empty($value)) {
        echo "EMPTY";
    } else {
        echo "Not empty";
    }

答案 2 :(得分:0)

对于您的问题,您需要

  1. 确认list2中的所有元素都显示在list1
  2. list2中的任何元素都不会出现在list2
  3. 使用collections.Counter

    可以非常轻松地完成此操作
    import collections
    
    def f(list1, list2):
        d1 = collections.Counter(list1)
        d2 = collections.Counter(list2)
        return set(d1.keys()).issuperset(set(d2.keys())) \
           and all(d2[k] <= d1[k] for k in d1.keys())
    

    首先检查(使用set.issupersetlist2中包含list1的所有不同元素。如果这是真的,它会检查每个元素在list2中出现的频率,并验证它在list1中出现频率较低(或同等频率)。

答案 3 :(得分:-2)

您可以使用issuperset

>>> list1 = ['a', 'b', 'c', 'b', 'i']
>>> list2 = ['a', 'c', 'b', 'b']
>>> set(list1).issuperset(set(list2)) # all items of list2 exist in list1
True
>>> set(list2).issuperset(set(list1)) # all items of list1 does not exist in list 2
False

答案 4 :(得分:-2)

尝试迭代list2并在找到时从list1中删除元素:

list1 = ['a','b', 'c', 'b', 'i']
list2 = ['a', 'c', 'b', 'b']
for elem in list2:
    try:
        del list1[list1.index(elem)]
    except ValueError:
        return False
return True

如果您需要保留list1,请事先复制

相关问题