Python Forum
Balance integer list into multiple list of fixed value
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Balance integer list into multiple list of fixed value
#1
Hi all,

I am trying to split the given list into multuple lists where the value limit for such splitted-list will be 10.

For example, given a list, eg. init_list = [1, 2, 3, 1, 7, 4, 5, 11], I am trying to split init_list into 3 different lists where each list each list only holds up to a max value of 10.
It will either fills up with as many as integers that adds up to 10, or integers closest to 10..

And if there are any integers not used, those integers will be appended in another list and so the results would be something as follows:

list01 = [1, 1, 2, 3, 4]
list02 = [7]
list03 = [5]

# unused
unused = [11]
So far I have managed to get it to split the list into 3 different lists, but I am unable to get the portion of setting the max value of 10 or, appending only the integer(s) closest to 10..
init_list = [1, 2, 3, 1, 7, 4, 5, 11]

def split_list(given_list, n):
    result = [[] for i in range(n)]
    sums   = [0]*n
    i = 0
    for e in given_list:
        result[i].append(e)
        sums[i] += e
        i = sums.index(min(sums))
    return result

split_list(init_list, 3)
Not exactly sure if this is the right way to approach this, or if anyone can kindly advise any other topics that I can try looking into?
Reply


Messages In This Thread
Balance integer list into multiple list of fixed value - by xenas - Oct-25-2018, 09:40 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Strange behavior list of list mmhmjanssen 3 379 May-09-2024, 11:32 AM
Last Post: mmhmjanssen
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,305 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  How to do "fixed size" (wrapping) math in Python? AlexanderWulf 13 2,055 Jul-19-2023, 04:13 PM
Last Post: deanhystad
  Fixed colum width for rowLabels i Matplotlib pandabay 0 453 Jun-10-2023, 03:40 PM
Last Post: pandabay
  Delete strings from a list to create a new only number list Dvdscot 8 1,651 May-01-2023, 09:06 PM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 965 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,929 Oct-26-2022, 04:03 PM
Last Post: deanhystad
Question Keyword to build list from list of objects? pfdjhfuys 3 1,635 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
  Selling gives me ‘Insufficient balance’ error gerald 3 1,625 Aug-04-2022, 10:16 AM
Last Post: Larz60+
  Split a number to list and list sum must be number sunny9495 5 2,373 Apr-28-2022, 09:32 AM
Last Post: Dexty

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020