python - How to create a random variable to be used as another variable in python
问题描述
I have a list of variables that hold specific links to sites. I want to set a variable to open a random one but whenever I set 'randvid' it becomes a string rather than the variable that I want to use. Here's an example of my code:
import random
import webbrowser
vid1 = 'link1'
vid2 = 'link2'
vid3 = 'link3'
n = random.randint(1,3)
randvid = 'vid' + str(n)
webbrowser.open_new(randvid)
解决方案
您可以在此处使用 random.choice:
random.choice([vid1, vid2, vid3])
该文档可以位于此处,但基本上,它从序列中选择一个随机项目,例如列表。通过从您定义的变量选项中构建一个列表,您可以使用 random.choice 随机选择一个项目。
如果您需要能够重现您的结果,您可以将 random.choice 与 random.seed 结合使用:
random.seed(1000)
random.choice([vid1, vid2, vid3])
推荐阅读
- r - geom_bar 如何使多个系列不堆叠
- java - 如何从数组或列表中删除两个元素的序列?
- c - 错误:使用无效的预处理令牌形成粘贴
- python - 'ImageDataGenerator' 对象没有属性 'image_data_generator'
- android - gradle 如何确定从哪个存储库安装?
- forms - access 2016:使用 Alt+Tab 在打开的表单之间切换
- php - 带有恶意代码的 Joomla K2 页面
- html - Google Chrome / macOS:密码字段不接受非 ASCII 字符
- django - 如何在 django REST 框架中返回模型的所有图像
- amazon-web-services - 如何使用我当前的代码将下载文件上传到亚马逊 s3 存储桶