Stack Overflow Asked by ripj on November 12, 2021
I want to append in an output-list every letter or letter sequence that are in list (for sequence letter, I replace with 0 incoming elements so that it can be ignored).
What I do not understand is why my loop is not iterating correctly through the list, it only finds one occurence of "okj".
s = "okjokjokj"
l = []
for i in s:
l.append(i)
dico = ["a", "bc", "okj"]
output = []
for i in l:
if i + l[l.index(i)+1] + l[l.index(i)+2] in dico:
print (i+l[l.index(i)+1]+l[l.index(i)+2], "found")
output.append(i + l[l.index(i)+1] + l[l.index(i)+2])
l[l.index(i)+1] = "0"
l[l.index(i)+2] = "0"
print(l)
if i + l[l.index(i)+1] in dico:
print (i+l[l.index(i)+1], "found")
output.append(i + l[l.index(i)+1])
l[l.index(i)+1] = "0"
print(l)
if i in dico:
print (i, "found")
output.append(i)
print(l)
if i == "0":
print ("nothing found")
print (l)
print("n output is", output)
output is :
okj found
['o', '0', '0', 'o', 'k', 'j', 'o', 'k', 'j']
nothing found
['o', '0', '0', 'o', 'k', 'j', 'o', 'k', 'j']
nothing found
['o', '0', '0', 'o', 'k', 'j', 'o', 'k', 'j']
output is ['okj']
After finding the first occurence, your list is:
['o', '0', '0', 'o', 'k', 'j', 'o', 'k', 'j']
So when your program run that line:
i + l[l.index(i)+1] + l[l.index(i)+2] in dico
It means for it : 'o' + '0' + '0'
because it takes the index of the first occurence of 'o'
in your list (index('o')=0)
Answered by Blacksad on November 12, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP