python - 如何从迭代器中随机选取一个元素?
阿神
阿神 2017-04-18 09:30:29
0
3
1309

如何从迭代器中随机选取一个元素?

random.choice(generaotr) 会提示 TypeError: object of type 'generator' has no len()

阿神
阿神

闭关修行中......

reply all(3)
PHPzhong

Signature: random.choice(seq), the parameter should be a sequence, first convert the generator to a sequence.

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template