請注意,您的問題指定輸入列表是一維的,但沒有給出指示到多少個項目每個邏輯行;你似乎神奇地暗示它應該是每行10個項目。
所以,對於一個一維列表,每行邏輯的項目,寬度和要求的瓷磚高度的數量,你可以這樣做:
def gettiles(list1d, row_items, width, height):
o_row= 0
row_count, remainder= divmod(len(list1d), row_items)
if remainder != 0:
raise RuntimeError("item count not divisible by %d" % row_items)
if row_count % height != 0:
raise RuntimeError("row count not divisible by height %d" % height)
if row_items % width != 0:
raise RuntimeError("row width not divisible by %d" % width)
for o_row in xrange(0, row_count, height):
for o_col in xrange(0, row_items, width):
result= []
top_left_index= o_row*row_items + o_col
for off_row in xrange(height):
for off_col in xrange(width):
result.append(list1d[top_left_index + off_row*row_items + off_col])
yield result
>>> import pprint
>>> pprint.pprint(list(gettiles(range(100), 10, 2, 5)))
[[0, 1, 10, 11, 20, 21, 30, 31, 40, 41],
[2, 3, 12, 13, 22, 23, 32, 33, 42, 43],
[4, 5, 14, 15, 24, 25, 34, 35, 44, 45],
[6, 7, 16, 17, 26, 27, 36, 37, 46, 47],
[8, 9, 18, 19, 28, 29, 38, 39, 48, 49],
[50, 51, 60, 61, 70, 71, 80, 81, 90, 91],
[52, 53, 62, 63, 72, 73, 82, 83, 92, 93],
[54, 55, 64, 65, 74, 75, 84, 85, 94, 95],
[56, 57, 66, 67, 76, 77, 86, 87, 96, 97],
[58, 59, 68, 69, 78, 79, 88, 89, 98, 99]]
你可以給你的輸入樣本和你會想要輸出? – bwawok 2010-07-12 15:22:06
你是什麼意思「標準功能」?這聽起來像你正在尋找一種特定的代碼風格。爲什麼不解決完成工作的代碼? – 2010-07-12 15:26:18
是輸入'list' 1D?如果是這樣,在行 - 主要或列主要秩序? – MAK 2010-07-12 15:32:37