[英]Split a List into several Lists based on sum of List in python
This is my code: 这是我的代码:
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]
My question is I want to repeat the code for the new_list just created, but I don't know how.( I want it automatically split the list when the sum of the values in a list greater than total.) 我的问题是我想为刚刚创建的new_list重复代码,但我不知道如何(当列表中值的总和大于总数时,我希望它自动拆分列表。)
I want the result like this. 我想要这样的结果。
>>> 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]
Thanks all. 谢谢大家
How about putting them in a dictionary? 如何将它们放入字典中?
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_
Prints 打印
{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]}
And if you badly want the assignments you can do: 而且,如果您非常想分配作业,可以执行以下操作:
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_
Prints 打印
[30.3125, 13.75, 12.1875, 30.625, 18.125]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.