gpt4 book ai didi

python - 切片 python 列表

转载 作者:太空宇宙 更新时间:2023-11-04 09:20:32 25 4
gpt4 key购买 nike

如果我有一个 say '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 等等,直到结束

谢谢

最佳答案

请注意,您的问题指定输入列表是一维的,但没有说明每个逻辑行有多少项;你似乎神奇地暗示它应该是每行 10 个项目。

因此,给定一个一维列表、每行的逻辑项数、请求的图 block 的宽度和高度,您可以执行以下操作:

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]]

关于python - 切片 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3229677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com