You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何随机替换列表中指定元素的半数实例为反转字符串

实现方案

整体逻辑分为四步实现:

  1. 收集所有符合替换条件的元素的索引位置
  2. 计算需要替换的数量:取符合条件总数的一半,额外增加±1的随机浮动适配需求
  3. 从符合条件的索引中随机抽取对应数量的待替换位置
  4. 遍历原列表,仅将抽到的位置的单词替换为反转形式

完整代码示例

import random

def replace_half_target_words(words, target_words):
    # 收集所有符合替换条件的元素索引
    eligible_indexes = [idx for idx, word in enumerate(words) if word in target_words]
    total_eligible = len(eligible_indexes)
    if total_eligible == 0:
        return words
    
    # 计算替换数量,支持±1浮动,同时做边界校验
    replace_count = total_eligible // 2
    if total_eligible > 1:
        replace_count += random.choice([-1, 0, 1])
    replace_count = max(0, min(replace_count, total_eligible))
    
    # 随机抽取待替换的索引
    replace_indexes = random.sample(eligible_indexes, replace_count)
    
    # 生成结果列表
    return [word[::-1] if idx in replace_indexes else word for idx, word in enumerate(words)]

# 测试用例
words = ['hello', 'test', 'whatever', 'hello', 'apple', 'test', 'hello']
target_words = ['test', 'hello']
print(replace_half_target_words(words, target_words))

代码说明

  • target_words参数传入你指定的需要替换的单词列表,示例中对应['test', 'hello']
  • 仅对属于target_words的元素做处理,其他单词会原样保留
  • 用random.sample抽取待替换索引,保证不会重复选取同一个位置
  • 替换数量的边界校验避免出现小于0或大于总符合数的异常情况

内容的提问来源于stack exchange,提问作者adamshaw23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:36:01