具有不同结果的多个随机选择

时间:2015-06-17 15:15:25

标签: python random

我正在尝试在Python中创建一个随机NPC生成器 - 我上次尝试这个时,它是在PHP中,然后就是这样。 。 。奇怪的。我希望能够做的是多次调用字符串中定义的变量。我可以通过运行for i in range(n)循环来做到这一点,但每次都让我得到相同的随机选择。

我一直在寻找,而且我不完全确定我已经找到了如何多次调用该函数并且每次都得到不同的结果。

import random
gend = [ 'male', 'female' ]
race = [ 'Human', 'Elf', 'Orc', 'Halfling', 'Gnome', 'Half-Elf', 'Half-Orc', 'Outsider' ]
pers = [ 'leader-like, optimistic', 'bad-tempered, irritable', 'relaxed, peaceful', 'quiet, analytical' ]
hook = [ 'a chore that needs doing', "some concerns for another's well-being", 'an item that needs retrieving/delivering',
    'a grudge', 'a person/organization in their way', 'a target on his or her back', 'an indiscretion that needs covering up',
    'a debt that needs paying' ]
randgend = random.choice(gend)
randrace = random.choice(race)
randpers = random.choice(pers)
randhook = random.choice(hook)
print("A {} {}, with a {} disposition and {}.".format(randgend, randrace, randpers, randhook))

3 个答案:

答案 0 :(得分:0)

该行:

randgend = random.choice(gend)

randgend使[ 'male', 'female' ]成为单一随机选择,您基本上是在撰写:

randgend = 'male'  # or female, whichever gets picked first

如果你希望它是一个每次返回一个不同的随机选择的函数,你需要:

randgend = lambda: random.choice(gend)

(见the docs on lambda expressions)然后调用它:

print("A {} {}, with a {} disposition and {}.".format(
    randgend(),  # note parentheses
    ...,
))

或者,更容易,只需将呼叫转移到random.choice

print("A {} {}, with a {} disposition and {}.".format(
    random.choice(gend),
    ...,
))

答案 1 :(得分:0)

如果你想要一个功能。试试这个

def myrandfunction():
    randgend = random.choice(gend)
    randrace = random.choice(race)
    randpers = random.choice(pers)
    randhook = random.choice(hook)
    return ("A {} {}, with a {} disposition and {}.".format(randgend, randrace, randpers, randhook))

>>>print(myrandfunction())
"A female Elf, with a relaxed, peaceful disposition and some concerns for another's well-being."
>>>print(myrandfunction())
'A male Half-Orc, with a leader-like, optimistic disposition and an indiscretion that needs covering up.'

如果您不想重复句子,请使用itertools.product

>>>from itertools import product
>>>myrandoms = product(gend,race,pers,hook)

>>>"A {} {}, with a {} disposition and {}.".format(*[i for i in next(myrandoms)])
'A male Human, with a bad-tempered, irritable disposition and an item that needs retrieving/delivering.'
>>>"A {} {}, with a {} disposition and {}.".format(*[i for i in next(myrandoms)])
'A male Human, with a leader-like, optimistic disposition and an indiscretion that needs covering up.'

答案 2 :(得分:0)

你可以像这样使用它

print("A {} {}, with a {} disposition and {}.".format(random.choice(gend), random.choice(race), random.choice(pers), random.choice(hook)))