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

2024-04-25 03:30:25 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

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]

我的问题是,我想重复刚刚创建的新的\列表的代码,但我不知道如何操作(当列表中的值之和大于total时,我希望它自动拆分列表)

我想要这样的结果。你知道吗

>>> 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]

谢谢大家。你知道吗


Tags: 代码密码列表newlistreversetotalsum
1条回答
网友
1楼 · 发布于 2024-04-25 03:30:25

把它们放在字典里怎么样?你知道吗

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]

相关问题 更多 >