2016-04-21 90 views
0

假設我有一個項目列表,我們說整數,我想分割成幾乎相同大小的子列表。這是很容易做到numpy的...根據權重Python分割項目列表

MyList = range(30) 
numpy.array_split(MyList, 3) 

....或自定義代碼....

nSubLists = 3 
subList =[] 
i = 0 
for item in MyList: 
    for i in range(nSubList): 
    subList[i].append(item) 
    if i > nSubLists: 
    i = 0 
    else: 
    i = i + 1 

但現在假設我不想間平均分配項目存在。假設,我希望他們根據一些權重分配

例如,

wgtList1 = 20% 
wgtList2 = 30% 
wgtList3 = 50% 

其中%顯示我想在每個子列表中的原始列表中的項目的分數。顯然,如果列表沒有按照百分比或分數進行均勻分配,那麼它可能是最接近的整數分割。

將這種權重應用於Python中的列表拆分的最佳方式是什麼?

回答

0

我在Python的專家,但編程解決方案,我能想到的會是這樣的:

def split(original_list, weight_list): 
    sublists = [] 
    prev_index = 0 
    for 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 your list contains 
weight_list = [0.2, 0.3, 0.5] # This equals to your 20%, 30% and 50% 

sublists = split(my_list, weight_list)