【发布时间】:2018-12-27 07:08:12
【问题描述】:
我有一个唯一元素列表,比如说 [1,2],我想将它拆分为 k=2 个子列表。现在我想要所有可能的子列表:
[ [ [1,2],[] ], [ [1],[2] ], [ [2],[1] ], [ [],[1,2] ] ]
我想拆分为 1
[ [1, 2] ]
如何使用 Python 3 做到这一点?
更新:我的目标是获取 N 个唯一编号列表的所有可能分区,其中每个分区将有 k 个子列表。我想展示比上面展示的更好的例子,我希望我不会错过任何东西。所以对于列表 [1, 2, 3] 和 k=2 我想要下一个列表:
[
[ [1,2,3], [] ],
[ [2,3], [1] ],
[ [1,3], [2] ],
[ [1,2], [3] ],
[ [1], [2,3] ],
[ [2], [1,3] ],
[ [3], [2,3] ],
[ [], [1,2,3] ]
]
更新 2:到目前为止,我已经结合了两个建议,并且很少修改得到下一个代码:
def sorted_k_partitions(seq, k):
"""Returns a list of all unique k-partitions of `seq`.
Each partition is a list of parts, and each part is a tuple.
The parts in each individual partition will be sorted in shortlex
order (i.e., by length first, then lexicographically).
The overall list of partitions will then be sorted by the length
of their first part, the length of their second part, ...,
the length of their last part, and then lexicographically.
"""
n = len(seq)
groups = [] # a list of lists, currently empty
def generate_partitions(i):
if i >= n:
yield list(map(tuple, groups))
else:
if n - i > k - len(groups):
for group in groups:
group.append(seq[i])
yield from generate_partitions(i + 1)
group.pop()
if len(groups) < k:
groups.append([seq[i]])
yield from generate_partitions(i + 1)
groups.pop()
result = generate_partitions(0)
# Sort the parts in each partition in shortlex order
result = [sorted(ps, key = lambda p: (len(p), p)) for ps in result]
# Sort partitions by the length of each part, then lexicographically.
result = sorted(result, key = lambda ps: (*map(len, ps), ps))
return result
有了这个功能,我接下来可以做:
import itertools as it
k=2
S = [1, 2, 3]
for i in (range(k)):
for groups in sorted_k_partitions(S, k-i):
for perm in it.permutations(groups+[tuple() for j in range(i)]):
print(perm)
输出是:
((1,), (2, 3))
((2, 3), (1,))
((2,), (1, 3))
((1, 3), (2,))
((3,), (1, 2))
((1, 2), (3,))
((1, 2, 3), ())
((), (1, 2, 3))
我还不确定,这段代码是否给了我正确的解决方案,也许还有其他方法?
【问题讨论】:
-
@wim 抱歉,我在考虑更复杂的示例,已更新
-
你不能把一个列表放在一个集合中——它不是可散列的......所以不会以任何方式或形式发生——投票结束,因为不清楚你在问什么
-
@busybear 不是我想要的,你可以看到我有空子集
-
@PatrickArtner 可以提供帮助,现在我正在尝试为 [1, 2] 和 k=2 创建与我展示的相同的列表列表
标签: python python-3.x math partition