切片Python列表

1 投票
5 回答
660 浏览
提问于 2025-04-16 01:10

如果我有一个包含'n'个元素的列表(每个元素是一个字节),这个列表表示一个矩形的二维矩阵,我该如何将它分割成宽为w、高为h的矩形,从列表的第一个元素开始,只使用Python的标准函数呢?

举个例子:

l =  
 [ 1,2,3,4,5,6,7,8,9,10,  
   11,12,13,14,15....20.  
   21,22,23,24,25....30  
   .....    
   .................200]   

这些元素在一个一维列表中。

如果我们选择宽为2、高为3的矩形(w*h),那么第一个矩形会包含1, 2, 11, 12, 21, 22,第二个矩形会包含3, 4, 13, 14, 23, 24,依此类推,直到列表的末尾。

谢谢!

5 个回答

1

或者这个,这个也很简单。

def genMatrix(rows, cols, mylist):
   for x in xrange(rows):
      yield mylist[x*cols:x*cols+cols]

结果

>>> L = [1,1,1,1,2,2,2,2]
>>> list(genMatrix(2, 4, L))
[[1, 1, 1, 1], [2, 2, 2, 2]]
>>> L = [1,1,1,1,2,2,2,2,3,3,3,3]
>>> list(genMatrix(3, 4, L))
[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
2

注意,你的问题提到输入的列表是一维的,但并没有说明每一行应该有多少个项目;你似乎暗示每行应该有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]]
1
width = 6
height = 4
xs = range(1,25)
w = 3
h = 2

def subrect(x,y):
    pos = y*h*width+x*w
    return [xs[(pos+row*width):(pos+row*width+w)] for row in range(h)]

print [subrect(x,y) for y in range(height / h) for x in range(width / w)]

将矩阵分成以下几部分:

 1  2  3     4  5  6
 7  8  9    10 11 12

13 14 15    16 17 18
19 20 21    22 23 24

编辑:或者针对你给出的例子...

width = 10
height = 20
xs = range(1,201)
w = 2
h = 3

撰写回答