How to find the index of an item in a python list?

Possible duplicate:
How to find the positions of the maximum list?

Question from homework: Define a function censor(words,nasty)that takes a list of words, and replaces all words that look in the disgusting word CENSORED, and returns a censored list of words.

>>> censor([โ€™itโ€™,โ€™isโ€™,โ€™rainingโ€™], [โ€™rainingโ€™])
[โ€™itโ€™,โ€™isโ€™,โ€™CENSOREDโ€™]

I see a solution like this:

  • find the index nasty
  • replace the words matching this index with "CENSORED"

but i'm stuck looking for an index.

+3
source share
4 answers

. words , nasty. 'CENSORED' , .

:

0

list .index.

>>> l=['a','b','c']
>>> l.index('b')
1
+18

, .

Python , - :

censor = [ 'bugger', 'nickle' ]
word = 'bugger'
if word in censor: print 'CENSORED'

, censor.

, for. , , :

for index in len(words)):
   print index, words[index]

.

+1
source

You can use the convenient built-in function enumerate()to navigate through the items in the list. For instance:

def censor(words, nasty):
    for i,word in enumerate(words):
       if word...
0
source

Source: https://habr.com/ru/post/1773040/


All Articles