根据python中List的总和将List拆分为多个列表

时间:2017-08-07 12:07:24

标签: python python-3.x

这是我的代码:

list_ = [30.3125, 13.75, 12.1875, 30.625, 18.125, 58.75, 38.125, 33.125, 55.3125, 28.75, 60.3125, 31.5625, 59.0625]
total = 150.0
new_list = []

while sum(list_) > total:
    new_list.append(list_[-1:])
    list_ = list_[:-1]

new_list.reverse()

print(list_)
>>> [30.3125, 13.75, 12.1875, 30.625, 18.125]
print(new_list)
>>> [58.75, 38.125, 33.125, 55.3125, 28.75, 60.3125, 31.5625, 59.0625]

我的问题是我想重复刚刚创建的new_list的代码,但我不知道如何。(我希望它在列表中值的总和大于总数时自动拆分列表。)

我想要这样的结果。

>>> list_     = [30.3125, 13.75, 12.1875, 30.625, 18.125]
>>> new_list  = [58.75, 38.125, 33.125]
>>> new_list1 = [55.3125, 28.75, 60.3125]
>>> new_list2 = [31.5625, 59.0625]

谢谢大家。

1 个答案:

答案 0 :(得分:0)

如何将它们放入字典?

list_ = [30.3125, 13.75, 12.1875, 30.625, 18.125, 58.75, 38.125, 33.125, 55.3125, 28.75, 60.3125, 31.5625, 59.0625]
total = 150.0

dict_ = {}

sum_ = 0
i = 0

for item in list_:    
    # When sum + item > total reset sum and go to next key
    sum_ += item
    if sum_ + item > total:
        sum_ = 0
        i+= 1
    dict_.setdefault(i, []).append(item)

dict_

打印

 {0: [30.3125, 13.75, 12.1875, 30.625, 18.125],
 1: [58.75, 38.125, 33.125],
 2: [55.3125, 28.75, 60.3125],
 3: [31.5625, 59.0625]}

如果您非常想要分配,您可以这样做:

for key,value in dict_.items():
    if key == 0:
        exec("list_={}".format(str(value)))
    elif key == 1:
        exec("new_list={}".format(str(value)))
    else:
        exec("new_list{}={}".format(str(key-1),str(value)))

list_

打印

[30.3125, 13.75, 12.1875, 30.625, 18.125]