简体   繁体   English

在 Python 中随机替换列表中的元素

[英]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 ie I'd want my new list to look something like:我想随机替换列表中某些元素(存储在另一个列表中)的实例的一半(可以向下/向上舍入),例如“测试”和“你好”,用相反的词,即我' d 希望我的新列表看起来像:

['olleh', 'test', 'whatever', 'hello', 'apple', 'tset','olleh',......] (here I am working with the words test and hello) ['olleh', 'test', 'whatever', 'hello', 'apple', 'tset','olleh',......] (这里我使用的是 test 和 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.我知道要反转我可以简单地做reversed_words = [i[::-1] for i in words]但我更不确定随机选择一半的出现部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM