string - Python loops iteration to get a list of all indices of an element in a list -


i trying write function consumes string , character , produces list of indices occurrences of character in string.

so far have, gives me [].

def list_of_indices(s,char):      string_lowercase = s.lower()     sorted_string = "".join(sorted(string_lowercase))     char_list = list(sorted_string)      x in char_list:           = []           if x == char:               a.append(char_list.index(x))           return 

i don't understand why not yield answer. , has list of non-empty length.

anyone aware of how indices occurrences?

you're returning on first iteration of for-loop. make sure return statement outside scope of loop.

also, sure put a = [] before for-loop. otherwise, you're resetting list on each iteration of loop.

there problem char_list.index(x). return index of first occurrence of x, isn't want. should keep track of index looping (e.g. enumerate()).

and i'm not sure trying sort; looping through original string should sufficient.

lastly, note can loop on string directly; don't need convert list (i.e. char_list unnecessary).


note task can accomplished simple list comprehension:

>>> s = 'abcaba' >>> char = 'a' >>>  >>> [i i,c in enumerate(s) if c == char]  # <-- [0, 3, 5] 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -