作者sharkbay (Shark Bay)
看板Python
标题[问题] 穷举"将List中元素分群"的所有可能方法
时间Fri Jan 22 06:27:43 2021
目前已知这个方法能满足这个题目, 但是空间或运算量太大, 想请问有没有别的做法?
import itertools
powerset = lambda iterable: itertools.chain.from_iterable(
itertools.combinations(list(iterable), r)
for r in range(len(list(iterable)) + 1))
flatten = lambda list2d: [item for sublist in list2d for item in sublist]
x = list("abcd")
xx = [list(val) for val in list(powerset(x)) if 0 != len(val)]
xxx = [list(val) for val in list(powerset(xx)) if 0 != len(val)]
xxxx = [list(val) for val in xxx if x == list(sorted(flatten(val)))]
xxxx =
[[['a', 'b', 'c', 'd']],
[['a'], ['b', 'c', 'd']],
[['b'], ['a', 'c', 'd']],
[['c'], ['a', 'b', 'd']],
[['d'], ['a', 'b', 'c']],
[['a', 'b'], ['c', 'd']],
[['a', 'c'], ['b', 'd']],
[['a', 'd'], ['b', 'c']],
[['a'], ['b'], ['c', 'd']],
[['a'], ['c'], ['b', 'd']],
[['a'], ['d'], ['b', 'c']],
[['b'], ['c'], ['a', 'd']],
[['b'], ['d'], ['a', 'c']],
[['c'], ['d'], ['a', 'b']],
[['a'], ['b'], ['c'], ['d']]]
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 106.1.116.121 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1611268065.A.18F.html
1F:推 LP9527: tuple+ set几行就搞定了 01/22 13:28
3F:→ LP9527: 喔看错了 01/22 13:47
4F:推 sherees: itertools.combinations 01/22 14:55
6F:→ ro9956882: [['a','b'],['c']]我用['ab','c']表示 这样过程中不用 01/23 00:15
7F:→ ro9956882: 用到deepcopy 要转换格式做完再一次转 01/23 00:15
8F:→ ro9956882: 如果有重复元素(多个'a')就要再改一下 0.0 01/23 00:21
elements = list("abcdefghijl")
combinations = [[]]
for element in elements :
for i in range(len(combinations)):
for j in range(len(combinations[i])):
new = combinations[i][:]
new[j] += element
combinations.append(new)
combinations[i].append(element)
combinations = [list(sorted([list(c) for c in combination]))
for combination in combinations]
combinations = list(sorted(combinations))
我重抄一份在此
※ 编辑: sharkbay (106.1.116.121 台湾), 01/23/2021 00:50:44
def partition(collection):
global counter
if len(collection) == 1:
yield [collection]
return
first = collection[0]
for smaller in partition(collection[1:]):
for n, subset in enumerate(smaller):
yield smaller[:n] + [[first] + subset] + smaller[n + 1:]
yield [[first]] + smaller
google到一份新的code
※ 编辑: sharkbay (106.1.116.121 台湾), 01/23/2021 06:20:52