我正在嘗試編寫一個函數,它使用一個字符串和一個字符,併爲該字符串中該字符的所有出現產生一個索引列表。Python循環迭代獲取列表中元素的所有索引的列表
到目前爲止,這是我的,但它總是給我[]。
def list_of_indices(s,char):
string_lowercase = s.lower()
sorted_string = "".join(sorted(string_lowercase))
char_list = list(sorted_string)
for x in char_list:
a = []
if x == char:
a.append(char_list.index(x))
return a
我不明白爲什麼這不會產生答案。它必須是一個非空長度的列表。
任何人都知道如何獲得所有事件的指數?
相關:[?如何找到一個元素出現的所有列表(http://stackoverflow.com/questions/6294179/how -to-find-all-occurrence-of-of-a-element-in-a-list) – kojiro