最近一个月的时间,基本上都在加班加点的写业务,在写代码的时候,也遇到了一个有趣的问题,值得记录一下. 简单来说,需求是从一个字典(python dict)中随机选出K个满足条件的key.代码如下(python2.7): def choose_items(item_dict, K, filter): '''item_dict = {id:info} ''' candidate_ids = [id for id in item_dict if filter(item_dict[id])] if le
参考API:https://docs.scipy.org/doc/numpy/reference/routines.random.html 1. numpy.random.shuffle() API中关于该函数是这样描述的: Modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional
numpy.random.shuffle(x) Modify a sequence in-place by shuffling its contents. Parameters: x : array_like The array or list to be shuffled. Returns: None Examples >>> >>> arr = np.arange(10) >>> np.random.shuffle(arr) >>>
randomly choose a sample of k items from a list S containing n elements, the algorithm may be online (i.e. the input list is unknown beforehand) https://en.wikipedia.org/wiki/Reservoir_sampling ReserviorSampling(Source[..n], Result[..k]) { ; i <= k;
1.2 Simple Random Sampling Census, :全部信息 Sampling: 抽样方式: representative sample:有偏向,研究者选择自己觉得有代表性的sample probability sampling:使用随机数表不用研究者来抽样,较为客观(研究者可以选择自己觉得有代表性和没有代表性的sample) simple random sampling. simple random sampling with replacement, whereby a
random.shuffle()是一个非常实用但是又非常容易被忽略的函数,shuffle在英语里是"洗牌"的意思,该函数非常形象地模拟了洗牌的过程,即: random.shuffle(x)表示对列表x中的所有元素随机打乱顺序(若x不是列表,则报错).此函数会直接对x本身进行操作,函数的返回值为None,即如果想对列表x进行洗牌,须使用random.shuffle(x)的形式,而不能使用y=random.shuffle(x)的形式. 示例代码: import random x = [1,
huffle与permutation的区别 函数shuffle与permutation都是对原来的数组进行重新洗牌(即随机打乱原来的元素顺序):区别在于shuffle直接在原来的数组上进行操作,改变原来数组的顺序,无返回值.而permutation不直接在原来的数组上进行操作,而是返回一个新的打乱顺序的数组,并不改变原来的数组. 示例: a = np.arange(12) print a np.random.shuffle(a) print a print a = np.arange(12) p