如何依据索引列表调整目标列表的元素顺序?
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
iina, it should be moved to positionb[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 inbcorresponds to the target position of the element at the same index ina.- 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
相关产品推荐
相关产品推荐

