简体   繁体   中英

Python List - Return Index

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]

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]

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

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]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM