以下脚本从列表中包含的颜色渐变中创建RGB数组。数组'白菜'的元素是列表'黄瓜'的索引。下面的脚本创建了一个数组'花椰菜',其形状与'卷心菜'相同,但索引替换为'黄瓜'中相应的元组。 Numpy有更直接的方式来执行此程序吗?
from numpy import array, shape, zeros
cabbage = array([[0,3,2],[3,2,1],[3,1,0]])
cucumber=[(0,100,0),(0,150,0),(0,200,0),(0,255,0)]
rows ,cols = shape(cabbage)
cauliflower = zeros((rows,cols),dtype=object)
for row in range(rows):
for col in range(cols):
cauliflower[row,col]=cucumber[cabbage[row,col]]
print cauliflower
[[(0, 100, 0) (0, 255, 0) (0, 200, 0)]
[(0, 255, 0) (0, 200, 0) (0, 150, 0)]
[(0, 255, 0) (0, 150, 0) (0, 100, 0)]]
答案 0 :(得分:0)
Numpy支持fancy indexing:
>>> from numpy import array, shape, zeros
>>> cabbage = array([[0,3,2],[3,2,1],[3,1,0]])
>>> cucumber=array([(0,100,0),(0,150,0),(0,200,0),(0,255,0)])
>>> cucumber[cabbage]
array([[[ 0, 100, 0],
[ 0, 255, 0],
[ 0, 200, 0]],
[[ 0, 255, 0],
[ 0, 200, 0],
[ 0, 150, 0]],
[[ 0, 255, 0],
[ 0, 150, 0],
[ 0, 100, 0]]])