【问题标题】:Selecting a random list and then pulling information from that list选择一个随机列表,然后从该列表中提取信息
【发布时间】:2021-02-04 19:59:17
【问题描述】:

我知道如何附加和访问列表中的随机数据。我正在尝试随机化其中一个列表(A、B 或 C),然后使用这些列表中的数据。

是否像更改 random_list 以匹配实际的 List_A(或 b/c)一样简单?还是我做错了?

import random

All_Lists = ["List_A", "List_B", "List_C"]
List_A = ["Albert", "Apple", "3", "Alpaca", "4"]
List_B = ["Barbara", "Banana", "6", "Baboon", "3"]
List_C = ["Calvin", "Carrot", "1", "Cat", "0"]

rand_idy = int(random.random() * len(All_Lists))
random_list = All_Lists[rand_idy]
print(random_list)

【问题讨论】:

    标签: python list random


    【解决方案1】:

    如下更改All_Lists,并将其移至其他列表之后:

    All_Lists = [List_A, List_B, List_C]
    

    注意没有引号。

    通常,您不会通过命名它们的字符串来引用 Python 变量。另见:How do I create variable variables?

    【讨论】:

    • 感谢您的帮助!我想这很容易。
    猜你喜欢
    • 2016-05-14
    • 2021-01-16
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多