使用索引获得正确的标签?

2024-09-30 14:16:27 发布

您现在位置:Python中文网/ 问答频道 /正文

非常愚蠢的问题,因为我是python新手:

如果我有标签=['a','b','c','d'], 和indics=[2,3,0,1]

我应该如何使用每个索引获得相应的标签,以便获得:['c','d','a','b']


Tags: 标签新手indics
1条回答
网友
1楼 · 发布于 2024-09-30 14:16:27

有几个备选方案,其中之一是使用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)

输出

['c', 'd', 'a', 'b']

相关问题 更多 >

    热门问题