I have a list that I want to rearrange based on the position of the (key, value) pair of another list:
original_list = [50, 50, 30, 30, 30, 30, 30, 20, 20, 20, 10]
reference_list = [(3, 10), (0, 30), (1, 20), (2, 50)]
Here is what I want:
modified_list = [10, 30, 30, 30, 30, 30, 20, 20, 20, 50, 50]
CodePudding user response:
I fail to see what the key
s in the tuples of the reference_list
mean, but the order in the example seems to be given by the value
.
So first I extract the values and their index to a dict and sort using this dict (could probably be done in one step, but this seems more readable).
original_list = [50, 50, 30, 30, 30, 30, 30, 20, 20, 20, 10]
reference_list = [(3, 10), (0, 30), (1, 20), (2, 50)]
reference_indexes = {t[1]: i for i, t in enumerate(reference_list)}
original_list.sort(key=lambda x: reference_indexes[x])
original_list # [10, 30, 30, 30, 30, 30, 20, 20, 20, 50, 50]
CodePudding user response:
import numpy as np
unflattened = [[value] * original_list.count(value) for key, value in reference_list]
flattened = [item for sublist in unflattened for item in sublist]
print(flattened)