简体   繁体   中英

How to 2d truncate a 3d python list with no imports

NO numpy

So I have here a 3d list:

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

Basically each index (x,y) in (row,column) is a pixel with r,g,b. This list has 5x10=50 pixels. I want to truncate it so that the columns and rows to a specified amount like row=3, column=7 like this:

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]

You shouldn't use list as a variable name as you are overwriting the built-in list and this may cause unexpected behaviour in code that comes after this

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM