【问题标题】:Check for presence of a sublist in list with order kept, and allow wildcards检查列表中是否存在保留顺序的子列表,并允许使用通配符
【发布时间】:2021-09-06 10:34:18
【问题描述】:

我想检查一个子列表是否存在于另一个(更大的)列表中,并且元素的顺序完全相同。我也希望它允许通配符。例如,我有以下列表:

>>> my_lists
[[0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 2, 2],
[1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 0, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 2, 2, 1, 2, 2, 2, 1, 1, 2, 1, 1, 0, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 2, 1, 2, 1, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 1, 2, 1, 2, 2, 1, 1],
[0, 1, 1, 1, 1, 2, 2, 2, 1, 0, 0, 0, 2, 2, 1, 1, 0, 0, 1, 1, 0],
[1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 0, 0, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 2, 1, 1, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

还有子列表:[0, 0, 0, 1]。如果我想找出哪些列表包含这个确切的子列表,我可以做(取自here):

def my_func(_list, sub_list):
    n = len(sub_list)
    return any((sub_list== _list[i:i+n]) for i in range(len(_list)-n+1))

for l in my_lists:
    if my_func(l, [0, 0, 0, 1]):
        print(l)

... 它基本上使所有可能的子列表与sub_list 的长度相同,并检查是否有任何相等。我会得到以下输出,因为这些列表包含[0, 0, 0, 1]:

[1, 1, 1, 1, 0, 2, 1, 2, 1, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 1, 1, 2, 1, 2, 2, 1, 1]
[1, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

现在我还想添加通配符,这意味着我可以给子列表通配符元素。例如,现在我要查找子列表[*, *, 0, 0, 0, 1, *]。这里的星号意味着对于这些元素,值可以是列表中的任何内容。但是对于那些星号必须有一个值。子列表 [*, *, 0, 0, 0, 1, *] 现在将输出:

[1, 1, 1, 1, 0, 2, 1, 2, 1, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 0]
[1, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0]

请注意,现在[0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 不包括在内,因为此列表在[0, 0, 0, 1] 序列开始之前没有两个值。 [0, 0, 0, 0, 1, 1, 2, 1, 2, 2, 1, 1] 也是如此,它在序列之前也没有两个值。请注意,星号可以是 np.nan 之类的任何内容。

如何扩展上述代码以允许使用通配符?

【问题讨论】:

    标签: python list


    【解决方案1】:

    一种方法是在检查子列表时使用all 和跳过星号的if:

    def my_func(a_list, sub_list):
        n = len(sub_list)
    
        # list-level comparison is now via element-wise
        return any(all(sub_item == chunk_item
                       for sub_item, chunk_item in zip(sub_list, a_list[i:i+n])
                       if not np.isnan(sub_item))  # "is_not_asterisk" condition
                   for i in range(len(a_list)-n+1))
    

    我使用not np.isnan(...) 作为问题中提到的星号条件;但它可能是很多东西:例如,如果星号在子列表中的字面意思是 "*",那么那里的条件将更改为 if sub_item != "*"。

    以np.nan 为星号的示例:

    for a_list in my_lists:
        if my_func(a_list, [np.nan, np.nan, 0, 0, 0, 1, np.nan]):
            print(a_list)
    

    给予

    [1, 1, 1, 1, 0, 2, 1, 2, 1, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 0]
    [1, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0]
    

    all 如果可迭代对象为空,则返回 True,因此如果传递了全星号子列表,它将为所有候选者返回 True(只要它们的长度允许,any 将处理因为带有空可迭代对象的any 是False!)。

    【讨论】:

    • 谢谢!我最喜欢这个解决方案,因为它干净且易于理解。
    【解决方案2】:

    另一种解决方案,具有自定义比较功能:

    def custom_cmp(l1, l2):
        if len(l1) != len(l2):
            return False
    
        for a, b in zip(l1, l2):
            if a == "*":  # you can check here for b=='*' if you wish
                continue
            if a != b:
                return False
    
        return True
    
    
    def my_func(_list, sub_list):
        n = len(sub_list)
        return any(
            custom_cmp(sub_list, _list[i : i + n])
            for i in range(len(_list) - n + 1)
        )
    
    
    for l in my_lists:
        if my_func(l, ["*", "*", 0, 0, 0, 1, "*"]):
            print(l)
    

    打印:

    [1, 1, 1, 1, 0, 2, 1, 2, 1, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 0]
    [1, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0]
    

    【讨论】:

      【解决方案3】:

      如果我们创建一个SuperInt 类,它允许我们包装int,但使其等于另一个具有相同值的实例(或具有相同值的“普通”int)和 字符串'*',我们可以使用你已有的代码。

      WILDCARD = '*'
      
      class SuperInt(int):
          def __eq__(self, other):
              if not isinstance(other, self.__class__) and other == WILDCARD:
              # or
              # if isinstance(other, str) and other == '*': but there might be a caveat with that
                  return True
              return super().__eq__(other)
      

      将您的 my_lists 转换为使用 SuperInt 实例:

      for i, li in enumerate(my_lists):
          my_lists[i] = list(map(SuperInt, li))
      

      运行您已经拥有的完全相同的代码(只需将* 替换为上面定义的WILDCARD):

      def my_func(_list, sub_list):
          n = len(sub_list)
          return any((sub_list == _list[i:i+n]) for i in range(len(_list)-n+1))
      
      for l in my_lists:
          if my_func(l, [WILDCARD, WILDCARD, 0, 0, 0, 1, WILDCARD]):
              print(l)
      

      输出

      [1, 1, 1, 1, 0, 2, 1, 2, 1, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 0]
      [1, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0]
      

      【讨论】:

      • 感谢深空!我从没想过超级分类Int,有趣的解决方案。
      【解决方案4】:

      如果列表中的元素始终是单个字符(例如示例中的数字),您可以转换为字符串并使用 re 模块搜索您的主题。 这比@Mustafa Aydın 的答案快了 10 倍以上,而且在我看来,作为一个单行来写相当快。但当然它不适用于具有多字符元素的数据集。

      import re
      [l for l in my_lists if re.search('..0001.', ''.join(map(str, l)))]
      

      或者,使用filter:

      list(filter(lambda l: re.search('..0001.', ''.join(map(str, l))), my_lists))
      

      如果您需要使用建议的通配符格式将查询输入为列表:

      pattern = ['*', '*', 0, 0, 0, 1, '*']
      [l
       for l in my_lists
       if re.search(''.join(map(str, pattern)).replace('*', '.'),
                    ''.join(map(str, l)))
      ]
      

      【讨论】:

        【解决方案5】:

        问题已得到解答,但我喜欢将另一个选项视为“老派”。

        my_lists = [
            [0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 2, 2],
            [1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 0, 0, 1, 1, 1, 1],
            [1, 1, 1, 1, 2, 2, 1, 2, 2, 2, 1, 1, 2, 1, 1, 0, 0, 1, 1, 1, 1],
            [1, 1, 1, 1, 0, 2, 1, 2, 1, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 0],
            [0, 0, 0, 0, 1, 1, 2, 1, 2, 2, 1, 1],
            [0, 1, 1, 1, 1, 2, 2, 2, 1, 0, 0, 0, 2, 2, 1, 1, 0, 0, 1, 1, 0],
            [1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0, 0, 1, 0, 0, 0],
            [1, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0],
            [0, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 0, 0, 1, 1, 1, 1, 1, 1, 1],
            [0, 0, 1, 1, 0, 0, 0],
            [0, 0, 1, 1, 1, 1, 1, 2, 1, 1, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0],
            [0, 1, 1, 0, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1],
            [0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
            [0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        ]
        
        my_sub_list = [0, 0, 0, '*', 1]
        
        def my_function(_list, _sub):
            a = len(_list)
            b = len(_sub)
            x = 0                                              # sublist index
            y = 0                                              # list index
            while y < a:
                if (_sub[x] == _list[y]) or (_sub[x] == '*'):  # we have a match
                    x += 1                                     # increment sublist index counter
                    y += 1                                     # increment list index counter
                    if x == b:                                 # if sublist index equals sublist length, then we've found a match
                        print(_list)
                        return
                else:
                    if x > 0:                                   # We had a partial match
                        y -= x - 1                              # Resetting index counter to next index after previous match
                    else:
                        y += 1                                  # No match, so we're moving to the next index
                    x = 0                                       # Resetting sublist index to the beginning
        
        
        for l in my_lists:
            my_function(l, my_sub_list)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-27
          • 2011-11-05
          • 1970-01-01
          • 2017-12-27
          • 2015-07-27
          相关资源
          最近更新 更多