python - How to replace every 2nd specific word in a list -


i have list in python:

['banana', 'apple', 'john', 'banana', 'food', 'banana'] 

and want replace every second banana pear (this should result):

['pear', 'apple', 'john', 'banana', 'food', 'pear'] 

i have code:

with open('text,txt') f:     words = f.read().split()  words_b = [word if word != 'banana' else 'pear' word in words] 

you use list comprehension indices of banana , slicing every second of these indices , set corresponding list item pear:

>>> l = ['banana', 'apple', 'john', 'banana', 'food', 'banana'] >>> idx in [idx idx, name in enumerate(l) if name == 'banana'][::2]: ...     l[idx] = 'pear' >>> l ['pear', 'apple', 'john', 'banana', 'food', 'pear'] 

instead of comprehension , slicing use generator expression , itertools.islice:

>>> itertools import islice >>> l = ['banana', 'apple', 'john', 'banana', 'food', 'banana'] >>> idx in islice((idx idx, name in enumerate(l) if name == 'banana'), none, none, 2): ...     l[idx] = 'pear' >>> l ['pear', 'apple', 'john', 'banana', 'food', 'pear'] 

another possibility, if don't want change list in-place, creating own generator function:

def replace_every_second(inp, needle, repl):     cnt = 0     item in inp:         if item == needle:    # match?             if cnt % 2 == 0:  # second occurence?                 yield repl             else:                  yield item             cnt += 1          # increase counter         else:             yield item  >>> l = ['banana', 'apple', 'john', 'banana', 'food', 'banana'] >>> list(replace_every_second(l, 'banana', 'pear')) ['pear', 'apple', 'john', 'banana', 'food', 'pear'] 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -