如何在不导入的情况下2d截断3d python列表



无数字

所以我在这里有一个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)

最新更新