我正在寻找一种将整数列表分组到列表列表中的有效方法,其中原始项目的总和不超过给定数量。
请考虑这个整数列表:
[1, 1, 1, 1, 2, 2, 1, 3, 1, 1, 2]
应将其分组,以使项目总和不超过3:
[[1, 1, 1], [1, 2], [2, 1], [3], [1, 1], [2]]
答案 0 :(得分:1)
def group(lst, limit):
lim = 0
grp = []
for x in lst:
if x + lim > limit:
yield grp
grp = []
lim = 0
grp.append(x)
lim += x
yield grp
print list(group([1, 1, 1, 1, 2, 2, 1, 3, 1, 1, 2], 3))
答案 1 :(得分:1)
import itertools
def sumkey(n):
sc = [0, 0] # sum, count => group by
def keyfunc(x):
sc[0] += x
if sc[0] > n:
sc[1] += 1
sc[0] = x
return sc[1]
return keyfunc
xs = [1, 1, 1, 1, 2, 2, 1, 3, 1, 1, 2]
print([list(grp) for _, grp in itertools.groupby(xs, key=sumkey(3))])
在Python 3中,sumkey
可以使用nonlocal
编写如下:
def sumkey(n):
sum_, count = 0, 0
def keyfunc(x):
nonlocal sum_, count
sum_ += x
if sum_ > n:
count += 1
sum_ = x
return count
return keyfunc
答案 2 :(得分:0)
不是最聪明的解决方案,但干净又简单:
def makeList(inList, n):
aList = []
while len(inList) > 0 and sum(aList) + inList[0] <= n :
aList.append(inList.pop(0))
return aList
def groupLists(inList, n, outList = []):
if not n:
raise ValueError("Please enter a positive integer")
while len(inList):
outList.append(makeList(inList, n))
return outList
print groupLists([1,1,1,1,2,2,1,3,1,1,2], 3)