【问题标题】:How do I generate non-repeating random numbers in a while loop? (Python 3)如何在while循环中生成非重复随机数? (Python 3)
【发布时间】:2015-12-12 08:15:13
【问题描述】:

到目前为止我所拥有的是

import random
def go():
    rounds = 0
    while rounds < 5:
        number = random.randint(1, 5)
        if number == 1:
            print('a')
        elif number == 2:
            print('b')
        elif number == 3:
            print('c')
        elif number == 4:
            print('d')
        elif number == 5:
            print('e')
        rounds = rounds + 1
go()

输出最终会是一些类似的东西

e
e
c
b
e

如何使数字只使用一次并且字母不重复? (例如类似的东西)

a
e
b
c
d

提前致谢

【问题讨论】:

  • 你可以试试random.sample("abcde", 5)random library python 3
  • 您的具体代码示例表明您需要L = list("abcde"); random.shuffle(L),即获得"abcde" 字母的随机排列。

标签: python python-3.x random while-loop


【解决方案1】:

random.sample(population, k) 方法从长度为 k 的指定总体返回唯一值样本。

r = random.sample("abcde", 5)
for element in r:
    print(element)

【讨论】:

  • @zeurosis 如果它对你有用,请选择它作为接受的答案
  • 抱歉,我该怎么做?我没有经常使用这个网站
  • @zeurosis 点击帖子左侧upvote/downvote 图标下的复选标记
  • @zeurosis 你可能也想在你以前的问题上这样做;)
  • random.sample("abcde", 5)emulate random.shuffle() 的一种奇怪方式
猜你喜欢
  • 2018-06-29
  • 1970-01-01
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-27
  • 2017-11-10
相关资源
最近更新 更多