【问题标题】:Replacing elements in a list randomly in Python在Python中随机替换列表中的元素
【发布时间】: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),他忘了添加范围

标签: python list random nlp


【解决方案1】:

如果您需要反转other_list每个单词的一半实例,那么您必须对每个单词索引进行采样:

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

arr_words = np.array(words)
idx_lst = []
for w in other_list:
    idx = np.where(arr_words == w)[0]
    idx_lst.append(np.random.choice(idx,len(idx)//2))
chosen_idx = np.concatenate(idx_lst)
arr[chosen_idx] = [w[::-1] for w in arr[chosen_idx]]
new_list = arr.tolist()

输出:

['hello', 'tset', 'whatever', 'hello', 'apple', 'tset', 'olleh']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-19
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 2019-03-25
    • 2014-06-12
    • 2018-10-08
    相关资源
    最近更新 更多