3


我有一个列表
[1,2,3,4,5,6,7,8]
我想在 python 中将其转换为 [[1,2,3,4][5,6,7,8]] 。有人可以帮我吗

4

3 回答 3

8

要输入:

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)]
于 2013-07-05T07:44:15.237 回答
4

您可以使用 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]]
于 2013-07-05T07:43:19.820 回答
4

还有 numpy 方式(如果您的列表是数字或字符串的统一列表等)。

import numpy
a = numpy.array(lst)
nslices = 4
a.reshape((nslices, -1))
于 2013-07-05T07:47:14.930 回答