Reputation: 165
For the list below - "A" - I would like to return the index of the elements in "A".....except if the element in "A" equals 'SCR'. Given this list/ code:
INPUT:
A=['126.00', '9.00', '1.50', '9.50', '9.50', 'SCR', '19.00', '12.00']
B=[(A.index(i)+1) for i in A if not i=='SCR']
print(B)
OUTPUT:
[1, 2, 3, 4, 4, 7, 8]
Notice that 4 repeats.
The required output is:
[1,2,3,4,5,7,8]
Upvotes: 0
Views: 173
Reputation: 429
Try:
b=[]
for i in range(len(A)):
if A[i] != "SCR":
b.append(i+1)
print (b)
Explanation:
Upvotes: 0
Reputation: 1458
When you use list.index()
, it returns the first match. So when i='9.50' you get the index of its first occurrence.
To avoid that, you can do something like this:
A=['126.00', '9.00', '1.50', '9.50', '9.50', 'SCR', '19.00', '12.00']
B=[i+1 for i in range(len(A)) if not A[i]=='SCR']
print(B)
>>[1, 2, 3, 4, 5, 7, 8]
Upvotes: 0
Reputation: 92440
You can use enumerate()
to get the indices as you loop over the list:
A=['126.00', '9.00', '1.50', '9.50', '9.50', 'SCR', '19.00', '12.00']
B=[i for i, v in enumerate(A, 1) if v!='SCR']
# [1, 2, 3, 4, 5, 7, 8]
Upvotes: 4
Reputation: 62
Yeah it will repeat because python starts checking from the front one by one and as soon as it finds one it stops.
To get rid of this problem just delete the element at that index when found.
Also you can just do one thing--
A=['126.00', '9.00', '1.50', '9.50', '9.50', 'SCR', '19.00', '12.00'] B=[(i+1) for i in A if not i=='SCR'] print(B)
Upvotes: -1