Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: keep track of elements moving within a list

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?

like image 665
Matteo NNZ Avatar asked Jan 24 '14 11:01

Matteo NNZ


People also ask

How do you move an element in a list in Python?

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.

Does Python list maintain order of insertion?

Yes, the order of elements in a python list is persistent.


1 Answers

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.

like image 123
falsetru Avatar answered Oct 29 '22 17:10

falsetru