Python分割list

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

其中,each为每一个列表的大小,len(ls)/eachExact能够避免整除时向下取整,形成总的分组数量的减小。app

注意:分组数并非简单的len(ls)/each+1便可,由于有可能恰好整除,没有余数。ide

 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    
相关文章
相关标签/搜索