首页 > 解决方案 > 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)

标签: pythonpython-3.x

解决方案


您可以在此处使用 random.choice:

random.choice([vid1, vid2, vid3])

该文档可以位于此处,但基本上,它从序列中选择一个随机项目,例如列表。通过从您定义的变量选项中构建一个列表,您可以使用 random.choice 随机选择一个项目。

如果您需要能够重现您的结果,您可以将 random.choice 与 random.seed 结合使用:

random.seed(1000)

random.choice([vid1, vid2, vid3])

推荐阅读