【问题标题】:How to 2d truncate a 3d python list with no imports如何在没有导入的情况下 2d 截断 3d python 列表
【发布时间】:2021-06-05 04:07:30
【问题描述】:

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

基本上,(row,column) 中的每个索引 (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],
        ],
    ]

【问题讨论】:

  • 抱歉不能使用numpy
  • 可能是硬件要求

标签: python arrays multidimensional-array


【解决方案1】:
truncated = [[row[:7] for row in color[:3]] for color in list]

您不应该使用 list 作为变量名,因为您要覆盖内置的 list,这可能会导致后面的代码出现意外行为

【讨论】:

    【解决方案2】:
    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 2018-11-10
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      相关资源
      最近更新 更多