我正在尝试编写一个函数,它使用一个字符串和一个字符,并为该字符串中该字符的所有出现产生一个索引列表。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