+ 5
How to find index of second p?
letters=['p','q','r','s','p','u'] print(letters.index('p') _________________________ This will print index of first p , I wanna print index of second p,, how to print it? https://code.sololearn.com/cfwyDmLIFhQp/?ref=app
3 Antworten
+ 3
You find the index of the first p, and then slice away the first p and everything prior to it. Repeat the index method on the remaining list.
print(letters[letters.index('p')+1:].index('p'))
However, this gives you the index of p within the sliced list. In order to obtain the index of the second p within the original list, add the length of the part of the list which has been sliced away.
print(letters[letters.index('p')+1:].index('p') + letters.index('p')+1)
It's getting a little long, so let's see how we should simplify it.
Let 'p' be any generic object, obj.
Let letters.index(obj)+1 be cutLength.
We can generalize this algorithm as:
https://code.sololearn.com/cqjc3JHXBesm/?ref=app
where occur is the nth occurrence,
list is your list, and obj is the object which index you want to find.
+ 1
I tried print(lettera.count('p')) but it prints, how many times p occurred in the list