首页 > 解决方案 > Python在一个函数中组合多个List

问题描述

嗨,我坚持将所有列表合并为最终列表。代码是在给定主字符串的情况下找到子集字符串的可能组合。

该代码能够找到所有可能的组合,但是我不知道如何组合结果

#for 'abcd', given ['a','b','c','bc','d']

#the out put shall be
#[['a','b','c','d'],['a','bc','d']]
def canConstruct(target_string,words,memo=None,):

  if memo == None: memo = dict()
  
  if target_string in memo:
    return memo[target_string]
 
  if target_string == "": return []

  for word in words:
    if target_string.startswith(word):
      remainder_string = target_string[len(word):]
      bank =  canConstruct(remainder_string,words,memo)
      bank = [word] + bank
      print(bank)
  return bank

print(canConstruct('abcd',['a','bc','b','c','d']))

标签: pythonlist

解决方案


将结果收集到一个列表中:

# ...
if target_string == "":
    return [[]]  # result is list of lists!
result = []
for word in words:
    if target_string.startswith(word):
        remainder_string = target_string[len(word):]
        for cc in canConstruct(remainder_string, words, memo):
            result.append([word] + cc)
memo[target_string] = result
return result

推荐阅读