You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重新排列Numpy chararray而不触发TypeError错误?

解决BGGR字符列表转三维numpy chararray的TypeError问题

错误原因

你遇到的TypeError: list indices must be integers or slices, not tuple是因为bggr是普通Python列表,而非numpy数组。Python原生列表不支持[切片, 切片]这种元组形式的多维索引,只能逐维进行切片操作。而你用数字时代码能运行,大概率是当时无意中把bggr定义成了numpy数组(numpy数组支持多维切片)。

两种解决方案

方案1:将bggr转为numpy数组(推荐,代码改动最小)

直接把bggr从Python列表转换成numpy数组,这样就能沿用你原来的多维切片逻辑:

import numpy as np

# 将bggr定义为numpy数组
bggr = np.array([['B', 'G', 'B', 'G'],
                 ['G', 'R', 'G', 'R'],
                 ['B', 'G', 'B', 'G'],
                 ['G', 'R', 'G', 'R']])

test = np.chararray((4, 4, 3))
test[:] = ''
test[::2, ::2, 2] = bggr[0::2, 0::2]  # blue
test[1::2, ::2, 1] = bggr[1::2, 0::2]  # green
test[::2, 1::2, 1] = bggr[0::2, 1::2]  # green
test[1::2, 1::2, 0] = bggr[1::2, 1::2]  # red
print(test)

运行后会输出带字节前缀(b'B')的结果,这是np.chararray的特性,属于正常现象。

方案2:用列表推导式逐维提取元素

如果不想转换为numpy数组,可以通过列表推导式逐维切片提取bggr中的元素:

import numpy as np

bggr = [['B', 'G', 'B', 'G'],
        ['G', 'R', 'G', 'R'],
        ['B', 'G', 'B', 'G'],
        ['G', 'R', 'G', 'R']]

test = np.chararray((4, 4, 3))
test[:] = ''
# 逐维切片提取列表元素
test[::2, ::2, 2] = [row[0::2] for row in bggr[0::2]]  # blue
test[1::2, ::2, 1] = [row[0::2] for row in bggr[1::2]]  # green
test[::2, 1::2, 1] = [row[1::2] for row in bggr[0::2]]  # green
test[1::2, 1::2, 0] = [row[1::2] for row in bggr[1::2]]  # red
print(test)

内容的提问来源于stack exchange,提问作者StraightFoward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 10:30:59