简体   繁体   中英

Python List indexing for finding number of the indexed element if the element is the same

Im trying to find the indexed version for multiple items in a list, such as

testarray = ["l","hello","l","l"]

for x in testarray:
    if x == "l":
        print(testarray.index(x))

I want the desired output to be 1, 3, 4 , but what I'm getting is 1,1,1

That's because list.index returns the index of the first occurrence of the element, to fix this, you can loop through the indices and values using enumerate :

testarray = ["l", "hello", "l", "l"]

for i, x in enumerate(testarray, 1):
    if x == "l":
        print(i)

Output:

1
3
4

In for i, x in enumerate(testarray, 1) , i in the index, x is the value, and the second parameter 1 in enumerate tells it to start counting at 1 instead of by default at 0 .

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