如何在python列表中查找某個元素的索引


如何在python列表中查找某個元素的索引


2019-03-15
百度上回復別人的問題,幾種方式的回答:
1print('*'*15,'想找出里面有重復數據的索引值','*'*15)
listA = [100, 94, 88, 82, 76, 70, 64, 58, 52, 46, 40, 34,76]
print('列表中第1次出現的位置 = ',listA.index(76))
2)
a_list = ['a','b','c','c','d','c']
find = 'c'
print('重復元素出現的位置索引分別是 = ',[i for i,v in enumerate(a_list) if v==find])

  ### print('重復元素出現的位置索引分別是 = ',[index for (index,value) in enumerate(a_list) if value==find])
       -----------------------------------------------------
 
        注解,語法(Copy from this help of Python): enumerate(iterable, start=0)

      Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. 
      enumerate() returns a tuple           ###這個值包含 (計數 值) 
               containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

        >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
        >>> list(enumerate(seasons))
        [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

        >>> list(enumerate(seasons, start=1))
        [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

 
         
 
         
 
         
      -----------------------------------------------------
3)### 求某個元素重復的索引值,函數方式表述如下:
a_list = ['a','b','c','c','d','c']
def unique_index(L,f):
"""L表示列表, i表示索引值,v表示values,f表示要查找的元素 """
return [i for (i,v) in enumerate(L) if v==f]
print('索引值 = ',unique_index(a_list,'c'))

運行結果:
索引值 = [2, 3, 5]

4)還缺一種,列出多個元素重復的索引值,以后再補充
...... 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM