繁体   English   中英

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

[英]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)

失败,返回 True。

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

失败,返回 True。

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

解决方案是什么? 尚未检查Numpy

使用计数器

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 的确切顺序很重要。 即这不会检查相反的顺序。

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

谢谢,

我想我不得不多搜索一点。

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

import numpy

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM