-4

I have a list like below:

['24', '24', '24', '24', '24', '1D', '1D', '1D', **'1D'**, **'24'**, '24', '24', '1D', '1D','24','24']

I want detect when the item changes from '1D' to '24' and I want to map the items to their corresponding indexes.

Like for this example the output should looks like:
{"1d":[8,13], "24":[9,14]}

Dcook
  • 899
  • 7
  • 32

1 Answers1

2

Is that what you want?

A = ['24', '24', '24', '24', '24', '1D', '1D', '1D', '1D', '24', '24', '24', '1D', '1D','24','24']
res = [[A[i], A[i + 1]] for i in range(len(A) - 1)] 
B = [index for index, value in enumerate(res) if value == ['1D','24']]
B
[8, 13] # feel free to add 1 if want to shift it to the second element position.

Edit:

A solution using numpy:

import numpy as np
A = ['24', '24', '24', '24', '24', '1D', '1D', '1D', '1D', '24', '24', '24', '1D', '1D','24','24']
sequence = ['1D','24']
# get all sequences
res = [[A[i], A[i + 1]] for i in range(len(A) - 1)]
# find index of such sequence
B = np.array([[i,i+1] for i, v in enumerate(res) if v == sequence]).T

# create an dict with sequences elements as keys and their 
# values as list of indexes:
mydict = {sequence[i]: list(B[i]) for i in range(len(sequence))} 


>>> mydict
{'1D': [8, 13], '24': [9, 14]}


More readings:

What does "list comprehension" mean? How does it work and how can I use it?
https://www.learnpython.org/en/List_Comprehensions
https://www.geeksforgeeks.org/python-consecutive-elements-pairing-in-list/ ...

swiss_knight
  • 5,787
  • 8
  • 50
  • 92