You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何依据索引列表调整目标列表的元素顺序?

Reordering a List Based on an Index Mapping List

Let's break down how to solve this problem where you need to rearrange elements of a target list according to an index list that specifies where each element should go.

Understanding the Problem

From your example:

  • Target list a = ["orange", "apple", "peach", "watermelon", "gum"]
  • Index list b = [3, 4, 1, 2, 0]
  • The rule: For each element at original index i in a, it should be moved to position b[i] in the new list. This gives us the final result ["gum", "peach", "watermelon", "orange", "apple"].

Efficient Solution in Python

The cleanest and most efficient way (O(n) time complexity) is to create a result list of the same length as a, then iterate through each element and place it in its designated position using the index list:

a = ["orange", "apple", "peach", "watermelon", "gum"]
b = [3, 4, 1, 2, 0]

# Initialize result list with placeholders
result = [None] * len(a)

# Iterate over original indices and their target positions
for original_idx, new_position in enumerate(b):
    result[new_position] = a[original_idx]

print(result)  # Output: ['gum', 'peach', 'watermelon', 'orange', 'apple']

Why This Works

  • enumerate(b) gives us pairs of (original_index_in_a, target_position_in_result) since each element in b corresponds to the target position of the element at the same index in a.
  • We start with a placeholder list to ensure we have space for every element, then fill it in exactly where each element belongs.

Alternative (Less Efficient) Approach

You might be tempted to use list comprehension with index(), but this has O(n²) time complexity (since index() scans the list each time), which is not ideal for large lists:

# Not recommended for large lists
result = [a[b.index(j)] for j in range(len(a))]

Stick with the first approach for better performance!

内容的提问来源于stack exchange,提问作者user3647488

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:57:11