python - 如何在初始化变量的结构之间随机选择?

标签 python

我正在尝试将字符串分配给变量,然后从这些变量中随机选择。

问题是我找不到方法:

  1. 从类或其他允许我初始化结构内变量的结构中随机选择,或者
  2. 从变量列表中进行选择,我不需要重复输入信息

理想情况下,我想要这样的东西:

class Websites:
    google = "https://google.com"
    twitter = "https://twitter.com"
    instagram = "https://instagram.com"

然后可以从中进行选择:

print(random.choice(Websites))

我还尝试创建伪 switch 语句:

from project.config import Websites

def switch_website(random_site):
    _ = Websites

    return {
         1: _.google
         2: _.twitter,
         3: _.instagram
    }[random_site]

但这需要我将变量名同时放入类和字典中,这是有问题的,因为最终的列表会非常大,并且稍后需要用额外的站点进行修改。

如果我使用了不正确的术语,我深表歉意,我昨天开始使用 Python。

感谢您的帮助!

最佳答案

您可以使用字典来实现此目的:

import random

Websites = {
    "google": "https://google.com",
    "twitter": "https://twitter.com",
    "instagram": "https://instagram.com",
}

print(random.choice(list(Websites.items())))

如果您只需要 URL 部分,请使用 values() 而不是 items():

print(random.choice(list(Websites.values())))

关于python - 如何在初始化变量的结构之间随机选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56046563/

相关文章:

掷骰子模拟器的Python数据结构

Python - 向量化滑动窗口

python - 从列表中删除包含列表的重复元组

python - 在任何类范围之外公开 Boost.Python 中的常量

python - pandas.Series.str.contains 无法检测到 "[a-zA-Z]"

python - 修改绘图轴,使其刻度标签的顺序和它们各自的点相应地改变——而不修改数据本身

python - Pip:指定次要版本

python - 用于迭代 2 个列表的简单 for 循环

python - 打包在 requirements.txt 中,但在 docker 中看不到

python - CherryPy 无法绑定(bind)到端口