【问题标题】:Random dictionary pick?随机字典选择?
【发布时间】:2021-05-03 11:51:15
【问题描述】:

我是python的新手,还在学习。在这里我遇到了一个我不知道如何解决的问题。

import random
materials = ["wood", "stone", "iron"]

wood = {
    "name": "wood",
    "weight": 50,
    "quality": 1
}

stone = {
    "name": "stone",
    "weight": 80,
    "quality": 2
}

iron = {
    "name": "iron",
    "weight": 110,
    "quality": 3
}

r = random.choice(materials)

基本上我想做的是打印一个特定的字典,这取决于 r - 随机选择。 有关如何正确执行此操作的任何提示?

【问题讨论】:

    标签: python dictionary random


    【解决方案1】:

    你应该使用对象类型而不是字符串,来自

    materials = ["wood", "stone", "iron"]
    

    materials = [wood, stone, iron]
    

    你也应该在分配这些对象后调用它。

    【讨论】:

    【解决方案2】:

    我想说只使用字典列表。在这种情况下,随机选择将是字典:

    import random
    
    materials = [{
        "name": "wood",
        "weight": 50,
        "quality": 1
    }, {
        "name": "stone",
        "weight": 80,
        "quality": 2
    }, {
        "name": "iron",
        "weight": 110,
        "quality": 3
    }]
    
    r = random.choice(materials)
    
    print(r)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-14
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      相关资源
      最近更新 更多