我有一份整体列表
list = [25, 50, 70, 32, 10, 20, 50, 40, 30]
如果它们的总和小于99,我想总结一下(从左到右)。让我说我把这个输出写成一个列表,而这个列表应该是这样的:
#75 because 25+50 = 70. 25+50+70 would be > 99
new_list = [75, 70, 62, 90, 30]
#70 because 70+32 > 99
#62 because 32+10+20 = 62. 32+10+20+50 would be > 99
但这不是全部。我想保存总和的总和。所以我真正想要的是一个如下所示的数据结构:
list0 = [ [(25,50),75], [(70),70], [(32, 10, 20),62], [(50, 40),90], [(30),30] ]
我该怎么做?
答案 0 :(得分:1)
使用单独的列表来跟踪您的号码:
results = []
result = []
for num in inputlist:
if sum(result) + num < 100:
result.append(num)
else:
results.append([tuple(result), sum(result)])
result = [num]
if result:
results.append([tuple(result), sum(result)])
对于您的样本输入,这会产生:
[[(25, 50), 75], [(70,), 70], [(32, 10, 20), 62], [(50, 40), 90], [(30,), 30]]
答案 1 :(得分:1)
您可以使用迭代器:
l = [25, 50, 70, 32, 10, 20, 50, 40, 30]
def sum_iter(lst):
s = 0
t = tuple()
for i in lst:
if s + i <= 99:
s += i
t += (i,)
else:
yield t, s
s = i
t = (i,)
else:
yield t, s
res = [[t, s] for t, s in sum_iter(l)]
您的数据结果是:
[[(25, 50), 75], [(70,), 70], [(32, 10, 20), 62], [(50, 40), 90], [(30,), 30]]