如何从迭代器中随机选取一个元素?
random.choice(generaotr)
会提示 TypeError: object of type 'generator' has no len()
PHPz2017-04-18 09:32:29
Signature: random.choice(seq)
, the parameter should be a sequence, first convert the generator to a sequence.
random.choice(list(generator))
ringa_lee2017-04-18 09:32:29
You can cache a certain number of iterator values first and then grab them randomly.
sets = list(zip(range(100),generator()))
choice = random.choice(sets)[1]
Or directly randomize an integer, and then next() all the way to that position.
黄舟2017-04-18 09:32:29
The question should be thought of like this: Since iterators are used, why do we need to randomly select numbers? What if the iterator is infinite? Of course, it can be converted into a list and will be discussed later