arrays - Python split list of items according to a weighting -
suppose have list of items, let's integers, split in near equal sized sub lists. that's easy numpy...
mylist = range(30) numpy.array_split(mylist, 3)
....or custom code....
nsublists = 3 sublist =[] = 0 item in mylist: in range(nsublist): sublist[i].append(item) if > nsublists: = 0 else: = + 1
but suppose don't want items distributed equally between subsists. suppose, want them distributed according weighting
e.g.
wgtlist1 = 20% wgtlist2 = 30% wgtlist3 = 50%
where % show fraction of items in original list want in each sub list. if list doesn't split evenly according percentages or fractions can closest integer split.
what's best way apply such weightings list split in python?
i no expert in python, programmatic solution can think of this:
def split(original_list, weight_list): sublists = [] prev_index = 0 weight in weight_list: next_index = math.ceil( (len(my_list) * weight) ) sublists.append( my_list[prev_index : next_index] ) prev_index = next_index return sublists ## function call ## my_list = [...] # whatever list contains weight_list = [0.2, 0.3, 0.5] # equals 20%, 30% , 50% sublists = split(my_list, weight_list)
Comments
Post a Comment