【问题标题】:How to make random.choice in a for loop give the same output every time如何使 for 循环中的 random.choice 每次都给出相同的输出
【发布时间】:2021-11-14 02:52:24
【问题描述】:

我正在重用别人编写的代码。它包含以下行:

 df = (random.choice(x) for i in repeat(0))

但是,因为没有random.seed,所以每次重新运行的时候输出都不一样,这是有道理的。

我尝试使用 random.Random(500).choice(x) 解决此问题,但由于它是一个 for 循环,因此每次迭代都会为我提供相同的值,这不是我想要的。

有人知道我是如何制作这个伪随机的吗? 谢谢!

【问题讨论】:

  • 你想要什么不清楚。您想从池中获取 n 个随机值吗?
  • 什么是x?它可能会被重新分配吗?
  • 如果你想从一个可迭代的x 中得到相同的随机值,重复n 次:[random.choice(x)]*n
  • @mozway 你将如何使用它来实现他们的目标?
  • 只需在循环外分配random.Random(500) 并在循环内使用?

标签: python random itertools random-seed


【解决方案1】:
import random

nums = [1, 2, 3, 4, 5]

def repeat_random(choices):
    i = 0
    chosen = random.choice(choices)
    while i < 5:
        print(chosen)
        i += 1

repeat_random(nums)

# 这将从 nums 列表中打印一个随机数 5 次

【讨论】:

    【解决方案2】:

    如果变量x 没有被重新分配:

    df = map(random.Random(500).choice, repeat(x))
    

    如果是这样:

    df = (choice(x)
          for choice in [random.Random(500).choice]
          for _ in repeat(0))
    

    Try it online!(参见“输出”部分)

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      相关资源
      最近更新 更多