【问题标题】:Check if list is composed by other lists检查列表是否由其他列表组成
【发布时间】:2013-12-23 03:45:30
【问题描述】:

我想找出列表m的哪些项目完全由列表w的项目组成。

如果我将它们添加到集合中并进行拦截,嵌入式结构将变得不可见,这正是我想要避免的。

案例:

w= [
     ['sta'], 
     ['co', 'si'], 
     ['non'], 
     ['si'], 
     ['puo'], 
     ['ap', 'ri', 're'], 
     ['ve', 'dia', 'mo'], 
     ['co', 'sa'], 
     ['ci'], 
     ['pot', 'reb', 'be']
   ]

m=[
     ['sta', 'co'], 
     ['puo', 'ap', 'ri', 're'], 
     ['ve'], 
     ['dia', 'mo'], 
     ['co'], 
     ['sa'], 
     ['ci', 'pot', 'reb', 'be']
  ]

期望的输出:

[['puo', 'ap', 'ri', 're'], ['ci', 'pot', 'reb', 'be']]

(例如,来自m['puo', 'ap', 'ri', 're'] 由来自w 的两个项目组成:[['puo'], ['ap', 'ri', 're']])。

谢谢大家!

【问题讨论】:

  • 您只想从手术中得到真/假答案吗?此外,除非列表很小,否则您似乎希望使用一个集合,然后在完成后将其丢弃,否则会很慢。
  • 原则上我还想要 m 中包含 w 中项目的项目列表。而且名单很大。

标签: python list recursion dynamic-programming nested-lists


【解决方案1】:

列表“list”的每个元素“elem”的算法递归检查是否(列表elem[1:]和列表elem[:1])或(列表elem[2:]和elem[: 2]) 或 ... 由列表 w 中包含的元素组成。 我还使用映射“内存”来优化使用记忆技术的算法。

def listInList(a, list, memory):
    if not list:
        return False
    elif str(list) in memory:
        return memory[str(list)]
    else:
        if list in a:
            memory[str(list)] = True
            return True
        else:
            for i in range(1,len(list)):
                if listInList(a, list[i:], memory) and listInList(a, list[:i], memory):
                    memory[str(list)] = True
                    return True
            memory[str(list)] = False
            return False

def check(a, b):
    res = []
    for elem in b:
        if listInList(a, elem, {}):
            res += [elem]
    return res

w= [
     ['sta'],
     ['co', 'si'],
     ['non'],
     ['si'],
     ['puo'],
     ['ap', 'ri', 're'],
     ['ve', 'dia', 'mo'],
     ['co', 'sa'],
     ['ci'],
     ['pot', 'reb', 'be']
   ]
m=[
     ['sta', 'co'],
     ['puo', 'ap', 'ri', 're'],
     ['ve'],
     ['dia', 'mo'],
     ['co'],
     ['sa'],
     ['ci', 'pot', 'reb', 'be']
  ]
print check(w,m)

输出:

[['puo', 'ap', 'ri', 're'], ['ci', 'pot', 'reb', 'be']]

【讨论】:

  • 所以如果我把它写到我的脚本中并打印出列表,我会得到一个比我应该拥有的更小的子列表。
  • 例如如果我使用列表 m 和 w,输出应该是:[['puo', 'ap', 'ri', 're'], ['ci', 'pot', 'reb', 'be ']]。你知道差异来自哪里吗?谢谢!
  • 好的,所以有点难。检查新算法,我已经编辑了旧算法。
  • 非常感谢!它实际上比我要复杂一些,但现在我得到了我需要的东西。
  • 我还有一个问题:listinList 函数在 b 的成员中查找 a 的所有成员,但如果列表较长,则它们不是精确的超集。如何更改函数以在 b 的成员中查找 a 成员的确切超集?
猜你喜欢
  • 2023-03-17
  • 2021-09-01
  • 2018-01-03
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
  • 2019-07-10
  • 2015-05-10
相关资源
最近更新 更多