0

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]
1
  • 2
    B = [index for item, index in enumerate(A) if item != "SCR"] Commented Sep 12, 2020 at 17:48

4 Answers 4

4

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Agreed @AndrejKesely, that is nicer.
Thanks - I'll brush up on 'enumerate'
0

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]

Comments

0

Try:

b=[]
for i in range(len(A)):
    if A[i] != "SCR":
        b.append(i+1)

print (b)

Explanation:

  • If we just need to print the index number, we can get it via "for i in range(len(A))". Here, it's value will be: 0,1,2,3,4,5,6,7
  • With if A[i] != "SCR", we are checking if value of that index is equals to SCR, if not, then add that index value to another array - B

1 Comment

Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users with similar issues.
-1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.