将列表拆分成更小的列表
我正在寻找一种方法来轻松地将python列表分成两半。
所以,如果我有一个数组:
A = [0,1,2,3,4,5] 我将能够得到:
 B = [0,1,2] C = [3,4,5] 
	
 A = [1,2,3,4,5,6] B = A[:len(A)/2] C = A[len(A)/2:] 
如果你想要一个function:
 def split_list(a_list): half = len(a_list)/2 return a_list[:half], a_list[half:] A = [1,2,3,4,5,6] B, C = split_list(A) 
一个更通用的解决scheme(你可以指定你想要的部分数量,而不是分成两半):
编辑 :更新后处理奇怪的列表长度
EDIT2 :根据Brians资讯性评论再次更新post
 def split_list(alist, wanted_parts=1): length = len(alist) return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts] for i in range(wanted_parts) ] A = [0,1,2,3,4,5,6,7,8,9] print split_list(A, wanted_parts=1) print split_list(A, wanted_parts=2) print split_list(A, wanted_parts=8) 
 f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)] f(A) 
  n – 结果数组的预定义长度 
 def split(arr, size): arrs = [] while len(arr) > size: pice = arr[:size] arrs.append(pice) arr = arr[size:] arrs.append(arr) return arrs 
testing:
 x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] print(split(x, 5)) 
结果:
 [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13]] 
 B,C=A[:len(A)/2],A[len(A)/2:] 
这是一个常见的解决scheme,将arr分成count部分
 def split(arr, count): return [arr[i::count] for i in range(count)] 
如果你不关心订单…
 def split(list): return list[::2], list[1::2] 
  list[::2]从第0个元素开始,获取列表中的第二个元素。 
  list[1::2]从第一个元素开始获取列表中的第二个元素。 
 def splitter(A): B = A[0:len(A)//2] C = A[len(A)//2:] return (B,C) 
我testing了,并且需要双斜杠来强制python3中的int分割。我原来的post是正确的,尽pipewysiwyg在Opera中出了问题,出于某种原因。
 对于将数组分割成n较小的数组的更广义的情况,有一个官方的Python receipe。 
 from itertools import izip_longest def grouper(n, iterable, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) 
这个代码片段来自Python的itertools文档页面 。
 使用列表切片 。 语法基本上是my_list[start_index:end_index] 
 >>> i = [0,1,2,3,4,5] >>> i[:3] # same as i[0:3] - grabs from first to third index (0->2) [0, 1, 2] >>> i[3:] # same as i[3:len(i)] - grabs from fourth index to end [3, 4, 5] 
 要获得列表的前半部分,请从第一个索引切换到len(i)/2 … 
 >>> i[:len(i)/2] [0, 1, 2] 
..交换价值左右,以获得下半场:
 >>> i[len(i)/2:] [3, 4, 5] 
 虽然上面的答案或多或less是正确的,但如果数组的大小不能被2整除,那么由于a / 2 ,a是奇数,在Python 3.0中是浮点数,而在早期版本,如果您from __future__ import division脚本的开始处的from __future__ import division指定。 在任何情况下,为了达到你的代码的“向前”兼容性,最好使用整数除法,即a // 2 。 
来自@ChristopheD的提示
 def line_split(N, K=1): length = len(N) return [N[i*length/K:(i+1)*length/K] for i in range(K)] A = [0,1,2,3,4,5,6,7,8,9] print line_split(A,1) print line_split(A,2) 
这与其他解决scheme类似,但速度稍快。
 # Usage: split_half([1,2,3,4,5]) Result: ([1, 2], [3, 4, 5]) def split_half(a): half = len(a) >> 1 return a[:half], a[half:] 
 #for python 3 A = [0,1,2,3,4,5] l = len(A)/2 B = A[:int(l)] C = A[int(l):]