如何在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)还缺一种,列出多个元素重复的索引值,以后再补充
...... 

 

posted @ 2020-05-24 10:49  CDPJ  阅读(5961)  评论(2编辑  收藏  举报