Home > Blockchain >  Indexing a list a element
Indexing a list a element

Time:10-06

Can you please help me here

Given a list of words (I.e. this list can take any number of strings, and strings are randomly positioned):

List1 = ['ENG', 'ENG', 'NEUTRAL' , 'TSO', 'ENG', 'TSO' ]

OR

List2 = ['NEUTRAL', 'NEUTRAL', 'ENG', 'ENG', 'NEUTRAL' , 'TSO', 'ENG', 'TSO', 'NEUTRAL']

I want to define the in index of this list. The index of NEUTRAL string must be -1. The index of other strings must be 0, 1, etc. In this order.

E.g. in list1, the index must be indexes = [0, 1, -1, 2, 3, 4]. List 2 indexes must be indexes = [-1, -1, 0, 1, -1, 2, 3, 4, -1]

Here is my attempt:

enter image description here

CodePudding user response:

You could use itertools.count to generate the counter and a list comprehension:

from itertools import count
c = count()

out = [next(c) if v!= 'NEUTRAL' else -1 for v in List1]

output: [0, 1, -1, 2, 3, 4]

output for "List2": [-1, -1, 0, 1, -1, 2, 3, 4, -1]

CodePudding user response:

Here is one of the approaches:

List1 = ['NEUTRAL', 'NEUTRAL', 'ENG', 'ENG', 'NEUTRAL' , 'TSO', 'ENG', 'TSO', 'NEUTRAL']
indexes = []
counter = 0
for element in List1:
    if element == 'NEUTRAL':
        indexes.append(-1)
    else:
        indexes.append(counter)
        counter  = 1
    
print (indexes)

Output:

[-1, -1, 0, 1, -1, 2, 3, 4, -1]
    
  • Related