简体   繁体   中英

Indexing of Same Values in a List

Due to list.index(x) will only return the index in the list of the first item whose value is x. Is there any way to return every index of same values in the list.

For example, I have a list containing some same values like:

mylist = [(A,8), (A,3), (A,3), (A,3)]

I want to return:

index_of_A_3 = [1, 2, 3]
mylist = [(A,8), (A,3), (A,3), (A,3)]
def indices( mylist, value):
    return [i for i,x in enumerate(mylist) if x==value]

print indices(mylist, (A,3))
# [1, 2, 3]

将 (A,3) 替换为您想要的或使用 lambda。

[i for i in range(len(mylist)) if mylist[i]==(A,3)]

有点丑,但是:

index_of_A_3 = [i for i in range(len(mylist)) if mylist[i] == (A,3)]

更快速 !!!!

index_of_A_3= np.where(mylist == (A,3))[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