lundi 6 décembre 2021

Replacing elements in a list randomly in Python

I have a list of words

words=['hello', 'test', 'whatever' , 'hello' , 'apple' , 'test','hello',......]

and I want to randomly replace half (can be rounded down/up by one) of the instances of some elements in the list (that are stored in another list) like 'test' and 'hello' with the the words reversed i.e I'd want my new list to look something like:

['olleh', 'test', 'whatever' , 'hello' , 'apple' , 'tset','olleh',......] (here I am working with the words test and hello)

How would I do this?

I know to reverse the words I can simply do reversed_words = [i[::-1] for i in words] but I'm more unsure about the randomly selecting half the occurances part.




Aucun commentaire:

Enregistrer un commentaire