从列表中获取随机样本,同时保持商品的顺序? [英] Get random sample from list while maintaining ordering of items?

查看:84
本文介绍了从列表中获取随机样本,同时保持商品的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个排序列表,可以说:(它不仅是数字,它是使用复杂的耗时算法排序的对象的列表)

I have a sorted list, let say: (its not really just numbers, its a list of objects that are sorted with a complicated time consuming algorithm)

mylist = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ,9  , 10 ]

是否有一些python函数可以给我N个项目,但会保持顺序?

Is there some python function that will give me N of the items, but will keep the order?

示例:

randomList = getRandom(mylist,4)
# randomList = [ 3 , 6 ,7 , 9 ]
randomList = getRandom(mylist,4)
# randomList = [ 1 , 2 , 4 , 8 ]

等...

推荐答案

以下代码将生成大小为4的随机样本:

Following code will generate a random sample of size 4:

import random

sample_size = 4
sorted_sample = [
    mylist[i] for i in sorted(random.sample(range(len(mylist)), sample_size))
]

(注意:在Python 2中,最好使用xrange代替range)

说明

random.sample(range(len(mylist)), sample_size)

生成原始列表的 indices 的随机样本.

generates a random sample of the indices of the original list.

然后对这些索引进行排序,以保留原始列表中元素的顺序.

These indices then get sorted to preserve the ordering of elements in the original list.

最后,给定采样索引,列表理解会从原始列表中拉出实际元素.

Finally, the list comprehension pulls out the actual elements from the original list, given the sampled indices.

这篇关于从列表中获取随机样本,同时保持商品的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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