3 回答
TA贡献1779条经验 获得超6个赞
试试这个:
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]]
TA贡献1864条经验 获得超6个赞
如果将列表本身作为第一个元素包含在内没有问题,您可以这样做:
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]]
TA贡献1828条经验 获得超6个赞
您可以通过递归使用列表切片:
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]]]
添加回答
举报