【问题标题】:How do you Build Random Items with Multiple Variables with Multiple Choices in Python?如何在 Python 中构建具有多个变量和多个选项的随机项?
【发布时间】:2013-04-18 23:05:07
【问题描述】:

我应该查看 Python 文档的哪个区域来完成以下任务:

npc_gender = ["Male","Female"]
npc_age = # trying to do random integer within a range say 18-80
npc_name_male = ["Arnold","Bob","Charles","David","Edward"]
npc_name_female = ["Annie","Barbara","Courtney","Danielle","Ellen"]
""" Obviously, the names are gender specific for an if/else statement :) """
npc_weight = # trying to figure out how to do range...not sure yet, but still variable.
npc_height = # same a weight...not sure yet.

def create_npc():
    if npc_gender == "Male"
        # select (automatically) one of the npc_name_male[#:] and store.
        return npc_name_male[#:]
    elif npc_gender == "Female"
        # select (automatically) one of the npc_name_female[#:] and store.
    else:
        return

现在我很困惑...基本上,我希望程序从已经存储在变量中的一系列参数中为我创建一个角色...

我是否朝着正确的方向前进?提前致谢。

对 Blender 的回应:

import random
npc_gender = ["Male","Female"]

def create_npc():
    npc_gender_choice = random.choice(npc_gender)
    print(npc_gender_choice)

create_npc()

我这样做了,它帮助我理解。我将继续努力,直到我完成所有工作,然后更新帖子。谢谢!

【问题讨论】:

    标签: python function python-3.x


    【解决方案1】:

    您可以使用random.choice() 来获取随机元素:

    import random
    
    ...
    
    choice = random.choice(npc_name_male)
    

    【讨论】:

    • 我这样做了,它有帮助!导入随机 npc_gender = ["Male","Female"] def create_npc(): npc_gender_choice = random.choice(npc_gender) print(npc_gender_choice) create_npc()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多