Python分割list

对于一个很大的列表,例如有超过一万个元素的列表,假如需要对列表中的每一个元素都进行一个复杂且耗时的计算,用单线程处理起来会很慢,这时有必要利用多线程进行处理,处理之前首先需要对大的列表进行分割,分割成小的列表,下面给出自己写的一个分割列表的方法:

其中,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    

 

posted @ 2016-04-25 21:31  morein2008  阅读(6393)  评论(0编辑  收藏  举报