1

我在 Python 中工作,基本上我有一个整数列表:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 10]

使用变量total,我试图弄清楚如何从这个列表中产生随机数(不替换),直到产生 10,然后停止。我想这会random.shuffle在一个while循环中使用,但我不确定。任何提示或建议?

4

2 回答 2

2

你 pop() 一个随机元素total,然后检查它是否是10. 例如:

while total.pop(random.randrange(len(total))) != 10:
     ... # do your stuff until the 10 is chosen

total.pop(i) 从totalindex 的元素中删除i,因此无需替换即可使用。另外,请查看此答案

编辑:
也许你试图通过多次使用相同的元素来实现加权随机选择;那将是一个相当丑陋的解决方案。在这种情况下,看看这个问题(Weighted random selection with and without replacement)是否有帮助。干杯。

于 2013-02-09T21:49:54.633 回答
1

使用random.shuffle甚至不需要循环。

random.shuffle(l)
random_selection = l[ :l.index(10) ]
于 2013-02-09T22:03:58.253 回答