[英]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.