如何从迭代器中随机选取一个元素?
random.choice(generaotr) 会提示 TypeError: object of type 'generator' has no len()
random.choice(generaotr)
TypeError: object of type 'generator' has no len()
闭关修行中......
Signature: random.choice(seq), the parameter should be a sequence, first convert the generator to a sequence.
Signature: random.choice(seq)
random.choice(list(generator))
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.
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
Signature: random.choice(seq)
, the parameter should be a sequence, first convert the generator to a sequence.You can cache a certain number of iterator values first and then grab them randomly.
Or directly randomize an integer, and then next() all the way to that position.
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