我有一份清单
[1,2,3,4,5,6,7,8]
我想在python中将其转换为[[1,2,3,4] [5,6,7,8]]。有人可以帮助我吗
答案 0 :(得分:7)
接受输入:
def chunks(l, n):
return [l[i:i+n] for i in range(0, len(l), n)]
mylist = [1,2,3,4,5,6,7,8]
while 1:
try:
size = int(raw_input('What size? ')) # Or input() if python 3.x
break
except ValueError:
print "Numbers only please"
print chunks(yourlist, size)
打印:
[[1, 2], [3, 4], [5, 6], [7, 8]] # Assuming 2 was the input
甚至:
>>> zip(*[iter(l)]*size) # Assuming 2 was the input
[(1, 2), (3, 4), (5, 6), (7, 8)]
答案 1 :(得分:3)
您可以使用itertools.islice
:
>>> from itertools import islice
def solve(lis, n):
it = iter(lis)
return [list(islice(it,n)) for _ in xrange(len(lis)/n)]
...
>>> solve(range(1,9),4)
[[1, 2, 3, 4], [5, 6, 7, 8]]
>>> solve(range(1,9),2)
[[1, 2], [3, 4], [5, 6], [7, 8]]
答案 2 :(得分:3)
还有一种numpy方式(如果你的列表是一个统一的数字或字符串列表等)。
import numpy
a = numpy.array(lst)
nslices = 4
a.reshape((nslices, -1))