【发布时间】:2022-01-11 21:25:43
【问题描述】:
我有一个单词列表
words=['hello', 'test', 'whatever' , 'hello' , 'apple' , 'test','hello',......]
并且我想随机替换列表中 一些 元素的实例(存储在另一个列表中)的 一半(可以向下/向上舍入) ) 比如 'test' 和 'hello' 的单词颠倒了,即我希望我的新列表看起来像:
['olleh', 'test', 'whatever' , 'hello' , 'apple' , 'tset','olleh',......]
(这里我使用的是 test 和 hello)
我该怎么做?
我知道把我可以简单做的词倒过来
reversed_words = [i[::-1] for i in words]
但我更不确定随机选择一半的出现部分。
【问题讨论】:
-
你可以生成一个长度为 len(words) 的随机列表并取一半?然后反转剩余列表的每个索引。
-
您可以使用“random.sample(len(words),len(words)//2)”获取要反转的单词索引列表
-
@MarkLavin 它说 Population 必须是一个序列或集合。对于 dicts,使用 list(d)。
-
random.sample(range(0,len(words)),len(words)//2),他忘了添加范围