Get random sample from list while maintaining ordering of items?

后端 未结 5 2090
清歌不尽
清歌不尽 2020-12-12 12:44

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          


        
5条回答
  •  Happy的楠姐
    2020-12-12 13:15

    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))
    ]
    

    (note: with Python 2, better use xrange instead of range)

    Explanation

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

    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.

提交回复
热议问题