使用zip:
>>> myStr = "01 02 03 04 11 12 13 14 21 22 23 24"
>>> n=4
>>> myList=[list(t) for t in zip(*[(int(x) for x in myStr.split())]*n)]
>>> myList
[[1, 2, 3, 4], [11, 12, 13, 14], [21, 22, 23, 24]]
或者
>>> myList=map(list,zip(*[(int(x) for x in myStr.split())]*n))
如果你不介意内部元素是元组还是列表,你可以这样做:
>>> zip(*[(int(x) for x in myStr.split())]*n)
[(1, 2, 3, 4), (11, 12, 13, 14), (21, 22, 23, 24)]
Zip 将截断任何不完整的组。如果您的行可能不均匀,请使用切片:
>>> myList=map(int,myStr.split())
>>> n=5
>>> [myList[i:i+n] for i in range(0,len(myList),n)] # use xrange on Py 2k...
[[1, 2, 3, 4, 11], [12, 13, 14, 21, 22], [23, 24]]
如果您想要 intertools 配方,请使用石斑鱼配方:
>>> from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
>>> map(list,grouper(map(int,myStr.split()),4))
[[1, 2, 3, 4], [11, 12, 13, 14], [21, 22, 23, 24]]