[英]How to 2d truncate a 3d python list with no imports
否 numpy
所以我这里有一个 3d 列表:
list = [
[
# red (5 rows x 10 columns)
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
],
[
# green (5 rows x 10 columns)
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
],
[
# blue (5 rows x 10 columns)
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10],
],
]
基本上,(行,列)中的每个索引(x,y)都是一个像素,r,g,b。 这个列表有 5x10=50 像素。 我想截断它,使列和行达到指定的数量,例如 row=3,column=7,如下所示:
list = [
[
# red (3 rows x 7 columns)
[10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10],
],
[
# green (3 rows x 7 columns)
[10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10],
],
[
# blue (3 rows x 7 columns)
[10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10, 10],
],
]
truncated = [[row[:7] for row in color[:3]] for color in list]
您不应该使用list
作为变量名,因为您正在覆盖内置list
,这可能会导致代码中出现意外行为
desired_rows = 3
desired_columns = 7
for i in range(len(list)):
list[i] = list[i][:desired_rows] # will give a 3x10 array
for j in (range(desired_rows)):
list[i][j] = list[i][j][:desired_columns] # will give a 3x7 array
print(list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.