Home > OS >  Loop or function that recognizes the corresponding item of each position
Loop or function that recognizes the corresponding item of each position

Time:04-10

I have the following list:

Nlist= [1,2,3,1,3,2,4,4,2,1,3,4,2,2]

And I would like to get this result:

result=["first appearance 1","first appearance 2","first appearance 3",3,2,4,"first appearance 4",1,3,6,6,4,1]

Note that the loop or function must identify the item from each position and subtract the previous position from the current position and so on until the end of the Nlist.

The best I could do by myself was the code below but it's not what I need.

from collections import defaultdict as cd

keys= cd(list); # create dictionary

for key,value in enumerate(Nlist):
    keys[value].append(key)
    # add the positions


import numpy as np

chav_test= keys[1] #select the key

key_test=np.diff(chav_test)

print(key_head)

Note that in the case of the code above I'm having to select the key of one of the items and what I'm looking for is a loop or function that is able to recognize the item from each position and subtract the current position from the previous position generating just a list end as a result. Could someone please help me to solve this problem? Thanks!

CodePudding user response:

You can iterate over the list while keeping track of the previous position of each item by storing those in a dictionary. Thus you can look up the previous position and construct the result list accordingly:

previous_position = {}
result = []

for index, item in enumerate(Nlist):
    if item in previous_position:
        result.append(index - previous_position[item])
    else:
        result.append(f'first appearance {item}')
    previous_position[item] = index
  • Related