列表的子列表

时间:2018-12-28 21:33:51

标签: python

我想要一个函数split_list([1,2,4,3]),它产生以下7个列表:

[[1], [2,4,3]]
[[1,2], [4,3]]
[[1,2,4], [3]]
[[1,2], [4],[3]]
[[1],[2,4],[3]]
[[1],[2],[4,3]]
[[1],[2],[4],[3]]

首先产生较小列表的地方-[[1], [2,4,3]]的长度为2,而[[1],[2],[4],[3]]的长度为4,这是因为它的长度为4。

def split_list(l):
  for i in range(1, len(l)):
    yield [l[:i],l[i:]]

for i in split_list((1,2,4,3)):
    print(i)

3 个答案:

答案 0 :(得分:1)

您可以通过递归使用列表切片:

def split_list(d):
   for i in range(len(d)):
      if len(d[i+1:]) > 0:
        for c in split_list(d[i+1:]):
          yield [d[:i+1], *c]
      else:
        yield [d]

print(list(split_list([1,2,4,3])))

输出:

[[[1], [2], [4], [3]], [[1], [2], [4, 3]], [[1], [2, 4], [3]], [[1], [2, 4, 3]], [[1, 2], [4], [3]], [[1, 2], [4, 3]], [[1, 2, 4], [3]], [[1, 2, 4, 3]]]

修改:活动时间缩短

def split_list(d):
  if len(d) > 1:
    return [list(filter(None, [d[:i+1], *c])) for i in range(len(d)) for c in split_list(d[i+1:])]
  return [d] if not isinstance(d, list) else [[d]]

输出:

[[[1], [2], [4], [3]], [[1], [2], [4, 3]], [[1], [2, 4], [3]], [[1], [2, 4, 3]], [[1, 2], [4], [3]], [[1, 2], [4, 3]], [[1, 2, 4], [3]], [[1, 2, 4, 3]]]

答案 1 :(得分:1)

如果将列表本身作为第一个元素是没有问题的,则可以这样:

def split_list(lst):
    if not lst:
        yield []

    for i in range(len(lst), 0, -1):
        for j in split_list(lst[i:]):
            yield [lst[:i]] + j


for l in split_list([1, 2, 4, 3]):
    print(l)

输出

[[1, 2, 4, 3]]
[[1, 2, 4], [3]]
[[1, 2], [4, 3]]
[[1, 2], [4], [3]]
[[1], [2, 4, 3]]
[[1], [2, 4], [3]]
[[1], [2], [4, 3]]
[[1], [2], [4], [3]]

答案 2 :(得分:1)

尝试这个:

def split_list(l):
    if len(l) == 1:
        yield [ l ]
        return

    for s in split_list(l[1:]):
        for n, sub in enumerate(s):
            if len((s[:n] + [[ l[0] ] + sub]  + s[n+1:])[0]) !=4:
                yield s[:n] + [[ l[0] ] + sub]  + s[n+1:]           
        yield [[l[0]]] + s

for lst in split_list([1, 2, 3, 4]):
        print lst

该问题以递归方式解决。 并在输出中:

[[1], [2, 3, 4]]
[[1, 2], [3, 4]]
[[2], [1, 3, 4]]
[[1], [2], [3, 4]]
[[1, 2, 3], [4]]
[[2, 3], [1, 4]]
[[1], [2, 3], [4]]
[[1, 3], [2, 4]]
[[3], [1, 2, 4]]
[[1], [3], [2, 4]]
[[1, 2], [3], [4]]
[[2], [1, 3], [4]]
[[2], [3], [1, 4]]
[[1], [2], [3], [4]]