Random sample from a very long iterable, in python

后端 未结 5 1810
南笙
南笙 2020-12-11 07:58

I have a long python generator that I want to \"thin out\" by randomly selecting a subset of values. Unfortunately, random.sample() will not work with arbitrary

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 08:21

    Use the itertools.compress() function, with a random selector function:

    itertools.compress(long_sequence, (random.randint(0, 100) < 10 for x in itertools.repeat(1)))
    

提交回复
热议问题