简体   繁体   中英

Get index of a sub list based on a reference list

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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM