【发布时间】:2020-11-29 23:44:21
【问题描述】:
鉴于:
- 字符串列表:
colors = ['red', 'blue', 'green', 'grey', 'black', 'yellow', 'brown', 'orange', 'magenta', 'cyan', 'teal', 'turquise']
-
a,numpy.array和a.shape[0]len(colors),其中包含一些数字(重复)值。
要求:
生成l 的列表str 对象,这些对象将匹配a 中的元素。 IE。对于a 中的每个元素,l 中都会有相同的str 对象,如Example 1 所示。
示例 1:
给定:
import numpy as np
colors = ['red', 'blue', 'green', 'grey', 'black', 'yellow', 'brown', 'orange', 'magenta', 'cyan', 'teal', 'turquise']
a = np.array([0, 1, 5, 7, 1, 5, 7, 7, 0, 0])
所需的输出应该是:
Out: ['red', 'blue', 'green', 'grey', 'blue', 'green', 'grey', 'grey', 'red', 'red']
我的解决方案:
我可以想到两种方法,如Code 1 和Code 2 所示。
代码 1:
import numpy as np
colors = ['red', 'blue', 'green', 'grey', 'black', 'yellow', 'brown', 'orange', 'magenta', 'cyan', 'teal', 'turquise']
a = np.array([0, 1, 5, 7, 1, 5, 7, 7, 0, 0])
num_2_color_dict = {}
for num in np.unique(a):
num_2_color_dict[num] = colors[np.min(np.where(a==num))]
color_by_num = []
for num in a:
color_by_num.append(num_2_color_dict[num])
color_by_num
Out: ['red', 'blue', 'green', 'grey', 'blue', 'green', 'grey', 'grey', 'red', 'red']
代码 2:
import numpy as np
colors = ['red', 'blue', 'green', 'grey', 'black', 'yellow', 'brown', 'orange', 'magenta', 'cyan', 'teal', 'turquise']
a = np.array([0, 1, 5, 7, 1, 5, 7, 7, 0, 0])
colors_by_num = [colors[np.min(np.where(np.unique(a)==num))] for num in a]
colors_by_num
问题:
我希望能够在不使用循环的情况下获得相同的结果,最好使用一些 numpy 数组操作技术,这将缩短代码。
提前致谢。
【问题讨论】:
标签: python python-3.x numpy