search

Home  >  Q&A  >  body text

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

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

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

阿神阿神2803 days ago1296

reply all(3)I'll reply

  • PHPz

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

    reply
    0
  • ringa_lee

    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.

    reply
    0
  • 黄舟

    黄舟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

    reply
    0
  • Cancelreply