小编pyt*_*ace的帖子

将变量分配给列表中的随机元素?蟒蛇

我想要一个阵列,里面会有大约30件事.数组中的每个东西都将是一组变量,并且根据选择数组中的哪个东西,将设置不同的变量.

例如

foo = ['fish', 'mammal', 'bird']
ranfoo = random.randint(0,2)
animal = foo[ranfoo]
Run Code Online (Sandbox Code Playgroud)

这适用于从列表中返回一个随机元素,但是,如何根据所选项目,我为它们分配一些变量?

例如'bird'已被随机选择,我想分配:flight = yes swim = no.或者沿着这些方向的东西......我编程的内容有点复杂,但基本上就是这样.我试过这个:

def thing(fish):
    flight = no
    swim = yes

def thing(mammal):
    flight = no
    swim = yes

def thing(bird):
    flight = yes
    swim = no

foo = ['fish', 'mammal', 'bird']
ranfoo = random.randint(0,2)
animal = foo[ranfoo]

thing(animal)
Run Code Online (Sandbox Code Playgroud)

但这也不起作用,我不知道还能做什么...帮助???

python arrays list

2
推荐指数
1
解决办法
3196
查看次数

我可以从列表中随机选择...但是如何将其用作不同命令的变量?蟒蛇

可以说我有以下内容:

foo = ('animal', 'vegetable', 'mineral')
Run Code Online (Sandbox Code Playgroud)

我希望能够从列表中随机选择THEN,具体取决于选择哪一个,具有一组要遵循的命令.

例如,如果随机选择"动物",我想要打印消息('rawr I \'ma tiger'),或者如果它是'蔬菜'打印('Woof,我是胡萝卜')或其他东西.

我知道随机选择它是:

from random import choice
print choice(foo)
Run Code Online (Sandbox Code Playgroud)

但我不希望打印的选择,我希望它是秘密的.请帮忙.

python printing random list choice

0
推荐指数
1
解决办法
350
查看次数

标签 统计

list ×2

python ×2

arrays ×1

choice ×1

printing ×1

random ×1