2024-09-30 14:16:27 发布
网友
非常愚蠢的问题,因为我是python新手:
如果我有标签=['a','b','c','d'], 和indics=[2,3,0,1]
我应该如何使用每个索引获得相应的标签,以便获得:['c','d','a','b']
有几个备选方案,其中之一是使用list comprehension:
labels = ['a', 'b', 'c', 'd'] indices = [2, 3, 0, 1] result = [labels[i] for i in indices] print(result)
输出
['c', 'd', 'a', 'b']
基本上迭代每个索引并在该位置获取项。上述等效于以下for循环:
result = [] for i in indices: result.append(labels[i])
第三种选择是使用operator.itemgetter:
from operator import itemgetter labels = ['a', 'b', 'c', 'd'] indices = [2, 3, 0, 1] result = list(itemgetter(*indices)(labels)) print(result)
有几个备选方案,其中之一是使用list comprehension:
输出
基本上迭代每个索引并在该位置获取项。上述等效于以下for循环:
第三种选择是使用operator.itemgetter:
输出
相关问题 更多 >
编程相关推荐