I have 2 lists:
reference_list = [a, z, c, m, e, k, g, n]
dynamic_list = [m, k, g] #Sorted following the same order as the reference list
I want to add e
to dynamic_list
, following the same order as for the reference_list
, and I want to know the index before inserting.
Something like:
index = get_index_dynamic_list(e, reference_list)
# Here I do some other stuff based on the index value
dynamic_list.insert(index, e)
CodePudding user response:
I guess you need an implementation for get_index_dynamic_list(e, reference_list)
function.
I implemented a function similar to this which takes the dynamic_list as an additional input. This seems to work when there are no duplicates elements in both lists. The function should be possible to change to handle duplicated also if you needed.
def get_index_dynamic_list(e, reference_list,dynamic_list):
index = 0
for i in range(len(reference_list)):
if reference_list[i] == e:
break
if reference_list[i] == dynamic_list[index]:
index = 1
return index
CodePudding user response:
I am not sure this is the cleanest or simplest way to do it, but I found this approach:
from bisect import bisect
reference_list = ['a', 'z', 'c', 'm', 'e', 'k', 'g', 'n']
dynamic_list = ['m', 'k', 'g'] #Sorted following the same order as the reference list
new_item= 'e'
ref_index = {v: i for i, v in enumerate(reference_list)}
dynamic_index = []
for item in dynamic_list:
dynamic_index.append(ref_index[item])
if new_item in reference_list:
index = bisect(dynamic_index, ref_index[new_item])
dynamic_list.insert(index, new_item)
else: # Add to the end element is not in the reference_list
dynamic_list.append(new_item)