I have a list of objects:
MyList = [A, B, C, D, E, F, G]
During the execution of the code, these objects might be moved of position. This movement usually happens one-by-one, so (for example) the item "D" might be moved right after "A". The list becomes, hence, as follows:
MyList = [A, D, B, C, E, F, G]
What I would like to know is if there's a method (I've already tried to build an algorithm but I would like to make the code shorter) to keep track of the elements over the list, so that I can use the indexes to recover them into the same list when I need to use them (the other parts of the code cannot be touched, otherwise I would implement this in the moving loops themselves). To explain better, I would like to know if it's possible to make something like this:
#ORIGINARY LIST
MyList = [A, B, C, D, E, F, G]
Current_Indexes= [0,1,2,3,4,5,6]
#ITERATION THAT MOVES D RIGHT AFTER A
MyList = [A, D, B, C, E, F, G]
Current_Index_Mapping = [0,3,1,2,4,5,6] #method or built-in function???
I have in mind something algorithmically, like creating a list at the beginning of the code like this:
for i in range(0, len(MyList)):
Current_Index_Mapping.append((i,MyList[i]))
and then extracting the tuples to update the Current_Index_Mapping list. However I'm pretty new to Python programming and I don't know lot of methods and built-in functions, so I was wondering: does anyone have a better idea to get the same result?
Method : Using pop() + insert() + index() In this we just use the property of pop function to return and remove element and insert it to the specific position of other list using index function.
Yes, the order of elements in a python list is persistent.
Map the id of objects to original indice:
>>> a, b, c, d, e, f, g = [object() for i in range(7)]
>>> lst = [a, b, c, d, e, f, g]
>>> objid_to_idx = {id(obj): idx for idx, obj in enumerate(lst)} # <---
# {
# id(a): 0,
# id(b): 1,
# ...
# id(g): 6,
# }
>>> [objid_to_idx[id(obj)] for obj in lst]
[0, 1, 2, 3, 4, 5, 6]
>>> lst = [a, d, b, c, e, f, g]
>>> [objid_to_idx[id(obj)] for obj in lst]
[0, 3, 1, 2, 4, 5, 6]
>>> lst = [a, d, b, a, c, e, e, f, g]
>>> [objid_to_idx[id(obj)] for obj in lst]
[0, 3, 1, 0, 2, 4, 4, 5, 6]
used dict comprehension, enumerate
to build mapping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With