随机排序有偏差的列表 [英] randomly sort a list with bias

查看:25
本文介绍了随机排序有偏差的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表如下:

I have a list as follows:

i = [
        {'id': '1', 'P': 0.5},
        {'id': '2', 'P': 0.4},
        {'id': '3', 'P': 0.8},
        ...
        {'id': 'x', 'P': P(x)}
    ]

当我执行以下操作时:

i.sort(key=lambda x: x['P'], reverse=True)

列表根据 P 排序,其中 P 最大的元素在前.但是,如果我想让它看起来是随机的,以便即使 P 值很小(概率很小)的元素也可以成为列表中的第一项,该怎么办?
是否可以使用 sort() 函数来实现,或者我必须自己编写?

The list gets sorted based on P where the element with the largest P is in front. but what if I want to make it seem randomized so that even a element with a small P value (with very small probability) can be the first item in the list?
Is it possible to implement that using the sort() function or do I have to write my own?

推荐答案

正如我在评论中提到的,您可以通过从标准正态分布中采样一个偏差因子来对随机偏差进行排序.然后,您可以将此偏差(零两侧对称)添加到您的 P 值中.

As I alluded to in a comment, you could sort with a level of random bias by sampling a bias factor from a standard normal distribution. You can then add this bias (which is symmetrical either side of zero) to your P value.

import numpy as np

#Give some control over the level of rearrangement - larger equals more rearrangement
bias_factor = 0.5

i.sort(key=lambda x: x['P'] + np.random.randn()*bias_factor, reverse=True)

或者如果您只想使用标准库:

Or if you just want to use the standard library:

from random import gauss

#Give some control over the level of rearrangement - larger equals more rearrangement
sigma = 0.5

i.sort(key=lambda x: x['P'] + gauss(0, sigma), reverse=True)

这篇关于随机排序有偏差的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆