Python 从索引列表和字符串列表中创建第三个列表

Python 从索引列表和字符串列表中创建第三个列表,python,list,Python,List,这可能是一个基本问题,但我甚至不知道如何恰当地表述它 我有两份清单: >>> indexes array([0, 2, 3, ..., 8, 5, 7]) # choices are between 0 and 8 >>> colors ['red', 'green', 'blue', 'orange', 'black', 'purple', 'yellow', 'grey', 'magenta'] 我想做一些不那么冗长、更像蟒蛇的事情: color_la

这可能是一个基本问题,但我甚至不知道如何恰当地表述它

我有两份清单:

>>> indexes
array([0, 2, 3, ..., 8, 5, 7]) # choices are between 0 and 8

>>> colors
['red', 'green', 'blue', 'orange', 'black', 'purple', 'yellow', 'grey', 'magenta']
我想做一些不那么冗长、更像蟒蛇的事情:

color_labels = []
for i in range(len(indexes)):
    color_labels.append(colors[indexes[i]])
尝试:

这使用了一个


你可以用理解力做其他很酷的事情!如果您使用parens
()
而不是方括号,则会得到一个,这类似于列表理解,只是它会被延迟计算。如果你使用大括号
{}
和冒号
你会得到一个,它可以让你快速地将元组列表等转换成字典。

z0r使用列表理解的答案肯定是最可读的

但是,您也可以使用以下功能:

color_labels = map(colors.__getitem__, indexes)

lambda

print map(lambda x: colors[x], indexes)

由于您的一个列表已经是
numpy
数组,您可以使用
numpy的
索引

color_labels = np.array(colors)[indexes]

谢谢我在找什么。
color_labels = np.array(colors)[indexes]