對於一個很大的列表,例如有超過一萬個元素的列表,假如需要對列表中的每一個元素都進行一個復雜且耗時的計算,用單線程處理起來會很慢,這時有必要利用多線程進行處理,處理之前首先需要對大的列表進行分割,分割成小的列表,下面給出自己寫的一個分割列表的方法:
其中,each為每個列表的大小,len(ls)/eachExact可以避免整除時向下取整,造成總的分組數量的減少。
注意:分組數並不是簡單的len(ls)/each+1即可,因為有可能剛好整除,沒有余數。
1 def divide(ls,each): 2 dividedLs=[] 3 eachExact=float(each) 4 groupCount=len(ls)/each 5 groupCountExact=len(ls)/eachExact 6 start=0 7 for i in xrange(groupCount): 8 dividedLs.append(ls[start:start+each]) 9 start=start+each 10 if groupCount<groupCountExact:#假如有余數,將剩余的所有元素加入到最后一個分組 11 dividedLs.append(ls[groupCount*each:]) 12 return dividedLs