Heim  >  Fragen und Antworten  >  Hauptteil

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

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

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

阿神阿神2741 Tage vor1240

Antworte allen(3)Ich werde antworten

  • PHPz

    PHPz2017-04-18 09:32:29

    Signature: random.choice(seq),参数应该是一个序列,先把 generator 转为序列。

    random.choice(list(generator))

    Antwort
    0
  • ringa_lee

    ringa_lee2017-04-18 09:32:29

    可以先缓存一定数量的迭代器的值,然后随机抓取。

    sets = list(zip(range(100),generator()))
    choice = random.choice(sets)[1]

    或者直接随机一个整数,然后一直next()到那个位置。

    Antwort
    0
  • 黄舟

    黄舟2017-04-18 09:32:29

    问题应该这样想:既然使用迭代器,为何又要随机取数?如果迭代器是无限大呢?当然,可转换成列表另讲

    Antwort
    0
  • StornierenAntwort