Python-如何生成具有多个范围的随机整数? [英] Python- How to generate random integers with multiple ranges?

查看:909
本文介绍了Python-如何生成具有多个范围的随机整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在从(a,b)的不同集合生成X数量的随机整数时,我陷入了困惑.例如,我想生成来自(1,5),(9,15)和(21,27)的5个随机整数.我的代码生成5个随机整数,但仅生成21到27之间的值,而不会生成其他两个整数.理想情况下,我希望看到的像是1,4,13,22,25,而不是21,21,25,24,27.

I've run into confusion in generating X amount of random integers from different sets of (a,b). For example, I would like to generate 5 random integers coming from (1,5), (9,15),and (21,27). My code generates 5 random integers but only between 21 and 27 and not from the other two. Ideally I'd like to see something like 1,4,13,22,25 instead of 21,21,25,24,27.

我的代码:

from random import randint
n = 0
while n < 5:
    n += 1
    for i in (randint(1,5),randint(9,15),randint(21,27)):
        x = i
    print i

推荐答案

不理想

from random import randint, choice

for _ in range(5):
    print(choice([randint(1,5),randint(9,15),randint(21,27)]))

就像Blender所说的-更清晰的版本

As Blender said - clearer version

from random import randint, choice

for _ in range(5):
    r = choice([(1,5),(9,15),(21,27)])
    print(randint(*r))

这篇关于Python-如何生成具有多个范围的随机整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆