【问题标题】:How do i use the random.choice of a list as a condition to what other lists to random.choice from?我如何使用列表的 random.choice 作为从其他列表中选择 random.choice 的条件?
【发布时间】:2012-03-17 11:49:41
【问题描述】:

例子:

element = ['Flaming', 'Cold']
fire_properties = ['of Fire', 'of Flame']
cold_properties = ['of Ice', 'of Frost']

相当简单。想要根据这个例子制作一个文本随机化器并最终得到诸如“火焰之剑”之类的结果。不幸的是,我不确定如何做到这一点,以便第一个列表的结果将定义第二个结果将来自哪个列表。

【问题讨论】:

    标签: python list random


    【解决方案1】:

    这样的解决方案怎么样:你构建一个形容词和名词的可能组合的映射并选择其中一个:

    weapon_map = {"Flaming": ["Fire", "Inferno"], "Frozen": ["Cold", "Frost"]}
    selection = random.choice(weapon_map.items())
    print (selection[0] + " of " + random.choice(selection[1]))
    

    这种方法更容易维护和理解。

    【讨论】:

    • 太糟糕了,在实际的编程课程开始之前,我从未见过你刚刚写的任何东西(除了“打印”)。甚至不确定“哈希”是什么。
    • @user1275670:那么我想说google.com/search?q=python+tutorial 可能是一个开始:)
    【解决方案2】:

    嗯,这是我第一次写的,但鲍里斯的更简洁,所以我决定不提交……不过,对于初学者来说可能更具可读性。

    quality_list =  ['Flaming', 'Frozen', 'etc.']
    quality = random.choice(quality_list)
    
    item_list = ['Sword', 'Dagger', 'Mace', 'etc.']
    item = random.choice(item_list)
    
    
    hot_qualities = ['Flaming', ...]
    cold_qualities = ['Frozen', ...]
    hot_elements = ['Fire', 'Inferno']
    cold_elements = ['Cold', 'Frost']
    
    if quality in hot_qualities:
        element = random.choice(hot_elements)
    elif quality in cold_qualities:
        element = random.choice(cold_elements)
    
    # NB this is Python 2.X's print and string format, adjust accordingly for 3.X
    print "%s %s of %s" % (quality, item, element)
    

    虽然在实际项目中,我会像鲍里斯那样进一步概括它。

    【讨论】:

    • 猜我可能会开始 Python 课程 :) 至于 in 关键字 - 阅读 this 或向下滚动到 Python reference 中的“in and not in”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 2014-05-17
    相关资源
    最近更新 更多