Possible Duplicate:
How to find positions of the list maximum?
A question from homework:
Define a function censor(words,nasty)
that takes a list of words, and
replaces all the words appearing in nasty with the word CENSORED, and
returns the censored list of words.
>>> censor([’it’,’is’,’raining’], [’raining’])
[’it’,’is’,’CENSORED’]
I see solution like this:
nasty
"CENSORED"
but i get stuck on finding the index..
Using enumerate with for-loop and if statement you can get the index of duplicate elements in python list.
To find the index of an element in a list, you use the index() function. It returns 3 as expected.
Indicate duplicate index values. Duplicated values are indicated as True values in the resulting array. Either all duplicates, all except the first, or all except the last occurrence of duplicates can be indicated. The value or values in a set of duplicates to mark as missing.
You can find the index of any element of a list
by using the .index
method.
>>> l=['a','b','c']
>>> l.index('b')
1
Actually you don't have to operate with indexes here. Just iterate over words
list and check if the word is listed in nasty
. If it is append 'CENSORED'
to the result list, else append the word itself.
Or you can involve list comprehension and conditional expression to get more elegant version:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With