Python transforming one dimensional array into two dimensional array
本问题已经有最佳答案,请猛点这里访问。
我有一个清单[1、2、3、4、5、6、7、8]我想用python将其转换为[[1,2,3,4][5,6,7,8]]。有人能帮我吗
接受输入:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 | [[1, 2], [3, 4], [5, 6], [7, 8]] # Assuming 2 was the input |
甚至:
1 2 | >>> zip(*[iter(l)]*size) # Assuming 2 was the input [(1, 2), (3, 4), (5, 6), (7, 8)] |
还有一种麻木的方式(如果你的列表是一个统一的数字或字符串列表,等等)。
1 2 3 4 | import numpy a = numpy.array(lst) nslices = 4 a.reshape((nslices, -1)) |
您可以使用
1 2 3 4 5 6 7 8 9 | >>> 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]] |