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

Python实现字典列表按EPC排序时随机保留部分元素不参与排序

你可以通过Python内置的random模块实现需求,完整实现代码如下:

import random

def sort_with_random_skip(offers):
    total = len(offers)
    if total == 0:
        return []
    # 计算20%~30%区间的不参与排序元素数量
    min_skip = int(total * 0.2)
    max_skip = int(total * 0.3)
    # 兼容短列表场景,避免抽取数量为0
    if max_skip < min_skip:
        min_skip, max_skip = max_skip, min_skip
    skip_count = random.randint(max(1, min_skip), max(max_skip, 1))

    # 通过索引抽取元素,避免字典判等误差
    all_indices = list(range(total))
    skip_indices = random.sample(all_indices, k=skip_count)
    unsorted_part = [offers[i] for i in skip_indices]
    sorted_part = [offers[i] for i in all_indices if i not in skip_indices]

    # 剩余元素按epc降序排序
    sorted_part.sort(key=lambda d: d['epc'], reverse=True)

    # 随机插入不参与排序的元素
    for item in unsorted_part:
        insert_pos = random.randint(0, len(sorted_part))
        sorted_part.insert(insert_pos, item)
    
    return sorted_part

# 调用测试
result = sort_with_random_skip(OFFERS)
# 输出验证epc排序效果
print([i['epc'] for i in result])

代码兼容了短列表场景,每次运行都会随机生成符合规则的排序结果,你可以根据业务需要调整边界数值的判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 12:48:03