使用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))
如果你不介意的內部元素的元組VS列表,你可以這樣做:
>>> zip(*[(int(x) for x in myStr.split())]*n)
[(1, 2, 3, 4), (11, 12, 13, 14), (21, 22, 23, 24)]
郵編會截斷任何不完整的組。如果有可能,你的行是不均勻的,用切片:
>>> 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]]
01可以是一個字符串,但如果它是一個整數,它會自動爲1。 – zhangyangyu
是的,這是正確的,我寫得很清楚。 –