2017-09-20 111 views
-2

这只返回列表中存在char的第一个索引值。我需要所有字符存在的指数。返回元素出现在python列表中的所有索引

def find_loc(char): 
    for sub_list in chunks: 
     if char in sub_list: 
       return chunks.index(sub_list), sub_list.index(char) 
+0

检举为 “质量很低”。看看[“我该如何提出一个好问题?”](https://stackoverflow.com/help/how-to-ask) –

+1

[如何查找列表中所有元素的出现? ](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) –

回答

0

索引方法返回遇到的第一个索引值。

帮助上method_descriptor:

index(...) 
    L.index(value, [start, [stop]]) -> integer -- return first index of value. 
    Raises ValueError if the value is not present. 
+0

是否有任何方法,我可以得到所有的索引值, –

+0

使用['enumerate'](http://book.pythontips.com/en/latest/enumerate.html),并提出一个条件。 – bhansa

+0

@shivamsinghal检查上面的链接进行枚举。 – bhansa

0

使用此片段:

def indexes(iterable, obj): 
    encounters = [] 
    for i in range(len(iterable)): 
     if iterable[i] == obj: 
      encounters.append(i) 
    return encounters 
相关问题