在python中,无论如何都有一个变量每次都是不同的随机数? [英] In python, is there anyway to have a variable be a different random number everytime?

查看:44
本文介绍了在python中,无论如何都有一个变量每次都是不同的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有这个:

随机导入variable1 = random.randint(13, 19)

基本上它的作用是为 variable1 分配一个 13 到 19 之间的随机数.很好.

但是,我想要它做的是在每次调用该变量时为该变量分配一个介于 13 和 19 之间的不同随机数.无论如何我可以做到这一点吗?

如果我不够清楚,这里有一个例子:

随机导入variable1 = random.randint(13, 19)打印(变量1)打印(变量1)打印(变量1)

我想要的输出看起来像这样:

./script.py151913

所以是的,无论如何我可以在 python 中做到这一点?(更具体地说是python3.但答案可能类似于python2答案)

解决方案

这接近你想要的

<预><代码>>>>随机导入>>>变量 1 = lambda: random.randint(13, 19)>>>打印(变量1())18>>>打印(变量1())15>>>打印(变量1())17>>>

Basically I have this:

import random
variable1 = random.randint(13, 19)

And basically what that does is assign variable1 a random number between 13 and 19. Great.

But, what I want it to do is assign a different random number between 13 and 19 to that variable every time it is called. Is there anyway I can do this?

If I'm not being clear enough here's an example:

import random
variable1 = random.randint(13, 19)
print(variable1)
print(variable1)
print(variable1)

And the output I want would look something like this:

./script.py
15
19
13

So yeah, anyway I could do this in python? (More specifically python3. but the answer would probably be similar to a python2 answer)

解决方案

This is close to what you want

>>> import random
>>> variable1 = lambda: random.randint(13, 19)
>>> print(variable1())
18
>>> print(variable1())
15
>>> print(variable1())
17
>>> 

这篇关于在python中,无论如何都有一个变量每次都是不同的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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