检查是否是另一个列表的列表子集(值可以重复)

check if a list subset of another list (values can be repetative)

我正在尝试检查列表 List2 是否是 python 3.8

List1 的子集

我尝试了 all()issubset() 函数,但它们都无法按照我的意愿过滤它 - 不幸的是,它们给出了 True - two 的元素实际上并不全部在 one,是吗?

List1 = [1,  4, 1, 3, 5]
 
List2 = [1 , 1, 1]

我尝试了什么:

check =  all(item in List1 for item in List2)

失败,returns正确。

flag = 0
if(set(List2).issubset(set(List1))): 
    flag = 1
print(flag)

失败,returns正确。

同时使用 intersection() 给出 True(实际上我不想要交集)。

解决这个问题的方法是什么?还没有检查 Numpy

谢谢,

我想我必须多搜索一点。

numpy isin() 方法不起作用,但这个看起来不错。

import numpy

arr = numpy.array([1,  4, 1, 3, 5])

print([1 , 1, 1] in arr.tolist())

但是首先我需要对我认为的数组进行排序...不确定

使用计数器

from collections import Counter 
  
def is_second_list_in_first(first_list, second_list): 
    ' checks if 2nd list of elements is in first list of elemetns with sufficient counts  '
     # get counts of two lists
    count_first = Counter(first_list) 
    count_second = Counter(second_list) 
  
    # check if count of elements exists in first list
    return all(count_second[key] <= count_first[key] for key in count_second)
    
# Tests
print(is_second_list_in_first([1,  4, 1, 3, 5], [1]))        # True
print(is_second_list_in_first([1,  4, 1, 3, 5], [1, 1]))     # True
print(is_second_list_in_first([1,  4, 1, 3, 5], [1, 1, 1]))  # False

这可能不是一个很好的解决方案,但您可以使用以下方法强制执行此操作:

def sub_list_check(main_list, sub_list):
    elm = 0
    last_elm = len(sub_list)-1
    for x in main_list:
        if x == sub_list[elm]:
            elm += 1
            if elm > last_elm:
                return True

        else:
            elm = 0
    
    return False

这是假设您的子列表 List2 的确切顺序很重要。也就是说,这不会检查颠倒的顺序。

如果您只是询问List1 中是否包含List2 元素,则使用集合。如果项目数量很重要,那么你不能使用集合,你可以使用集合库中的 Counter() 之类的东西。