【问题标题】:Checking for sublists in list of lists preserving sequence检查列表保留序列中的子列表
【发布时间】:2017-02-01 15:16:38
【问题描述】:

我有一个列表列表,其中每个列表包含一定数量的单词。每个列表的长度不必与其他所有列表的长度相同。基本上:

wordlist = [ ['cat', 'sheep', 'dog', 'pig', 'tomato'], ['apple', 'orange', 'sheep', 'dog' 'tomato'], ['cat', 'apple', 'sheep', 'tomato', 'dog'], ['garlic', 'tomato', 'dog' ]

我还创建了一个可以在所有列表中找到的常用单词列表,对于上面的示例,它将是:

common = ['sheep','dog', 'tomato']

我现在想检查一下,对于一个列表,如果常用词以某种顺序出现,那么在其他列表中这些词是否以相同的顺序出现。比如list1中常用词的出现顺序是['sheep', 'dog'],list2中出现的顺序相同,所以我应该返回:

list1: list2

在list3中['tomato','dog']依次出现,在list4中也是如此,所以这两个被映射了。使总输出如下:

list1: list2
list2: list1
list3: list4
list4: list3

如果 list1 具有与其他列表按顺序排列的公共子列表,它将打印为 list1:list2、list5、list7 等等。它应该适用于所有子列表。

有没有办法做到这一点?

【问题讨论】:

标签: python


【解决方案1】:

解决方案取决于您对列表的期望值。

如果存在重复值的可能性,并且您需要检查测试容器中是否有足够的值,那么这里是一个时间效率低的解决方案:

def contained(candidate, container):
    temp = container[:]
    try:
        for v in candidate:
            temp.remove(v)
        return True
    except ValueError:
        return False

使用以下方法测试此功能:

>>> a = [1,1,2,3]
>>> b = [1,2,3,4,5]
>>> contained(a,b)
False    
>>> a = [1,2,3]
>>> contained(a,b)
True
>>> a = [1,1,2,4,4]
>>> b = [1,1,2,2,2,3,4,4,5]
>>> contained(a,b)
True

【讨论】:

  • 不会有重复。我只是在寻找常用词以及它们在映射列表中出现的顺序到它们以相同顺序出现的其他列表。
  • 请提供您复制此答案的链接:stackoverflow.com/questions/2582911/…
  • 我得到一个 AttributeError: 'str' object has no attribute 'remove'
猜你喜欢
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-07
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多