Issue
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.)
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.
Solution
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]
Answered By - Anton vBR
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.