出于某些目的,我需要生成一个可迭代的对象,该对象列出列表的所有分区,但对子集的长度有条件。也就是说,如果列表的长度不是3的倍数,我想将列表划分为等长的子集(此处等于3),最后一个除外。
即['a','b','c','d','e']应该为所有分区分配2个长度为3和2的子集。
即,如果我只使用:
[p for p in multiset_partitions(['a','b','c','d','e'],2)] Out: [[['a', 'b', 'c', 'd'], ['e']], [['a', 'b', 'c', 'e'], ['d']], [['a', 'b', 'c'], ['d', 'e']], ..... [['a', 'd'], ['b', 'c', 'e']], [['a', 'e'], ['b', 'c', 'd']], [['a'], ['b', 'c', 'd', 'e']]]
我都明白了。因此,到目前为止,我最好的尝试是过滤出至少包含一个长度> 3的子集的分区:
from sympy.utilities.iterables import multiset_partitions def partitions(liste): compte = 0 n = len(liste)//3 + 1 for p in multiset_partitions(liste,n): l = len(p) oversize = False i = 0 while not(oversize) and i != l: if len(p[i])>3: oversize=True i+=1 if oversize == False: compte += 1 #do something with p return(compte) #I'm just counting out the number of partitions right now
这可以解决问题,但显然不是实现我想要的最有效方法。特别是当列表的长度增加时,分区的数量会迅速增加。
((长度为5时为10,但长度为10时为9100,13处为800800 ...)
最有效的pythonic方法应该是什么?
谢谢,
蒂埃里
出于某些目的,我需要生成一个可迭代的对象,该对象列出列表的所有分区,但对子集的长度有条件。也就是说,我想将列表划分为相等的子集...
通过在每次迭代中生成与您的条件匹配的分区,将partitions
变成生成器。
您总是可以将filter
包裹在分区功能周围。