Home > Mobile >  how to split the list into repeating sections?
how to split the list into repeating sections?

Time:01-29

how to split the list into repeating sections and store their indexes in the original line next to their value in the dictionary? I know it's not clear, but I think it will be clearer with an example

in the example, I break by characters, but the code should not be tied only to break by characters (I can also use break by '1' or '\' for example)

s = 'hello world' 
res = {'h' : [0], 'e' : [1], 'l' : [2, 3, 9], 'o' : [4, 7], ' ' : [5], 'w' : [6], 'r' : [8]}

CodePudding user response:

Simple way is to iterate through items and append them using enumerate:

s = "hello world"
d = {}
for j, i in enumerate(s):
    if i in d:
        d[i].append(j)
    else:
        d[i] = [j]

result is:

{'h': [0], 'e': [1], 'l': [2, 3, 9], 'o': [4, 7], ' ': [5], 'w': [6], 'r': [8], 'd': [10]}
  • Related