如何在中使用for循环迭代器作为动态值随机选择()从与i的值同名的列表中选择随机元素?

2024-10-01 00:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子叫“打孔”:

punch = ['dodges punch','catches fist','moves out of the way']

下面的代码将打印“punch”:

def bang(atk, atkL):
    for i in atk: 
       if i in atkL:  
          print i

但下面的代码不会从punch打印随机元素:

def bang(atk, atkL):
    for i in atk: 
       if i in atkL:  
          print (random.choice(i))

它不断打印单词punch中的一个字母('p'或'u'或'n'或'c'或'h')。你知道吗

此代码将从punch打印一个随机元素:

print (random.choice(punch))

如何将迭代器值添加到随机选择函数,以便打印冲压中的随机元素?你知道吗

def bang(atk, atkL):
    for i in atk: 
       if i in atkL:  
          print (random.choice(i))

Tags: 代码in元素forifdefrandom单子
2条回答
import random

punch = ['dodges punch','catches firdt','moves out of the way']

def bang(atk, atkL):
    for i in atk:
        if i in atkL:
            print(random.sample(punch,1))

bang(punch, punch)

使用此代码,因为我认为您正在寻找类似随机输出的东西。你知道吗

但是

random.choice(seq)

从非空序列seq返回一个随机元素。如果seq为空,则引发IndexError。你知道吗

我想你需要一本字典

moves = {
    "punch": ['dodges punch','catches fist','moves out of the way'],
    "kick":  [ ... ],
    "jump":  [ ... ],
}

然后你可以使用i = "punch"来获得随机穿孔

random.choice(moves[i])

或者i = "kick"得到随机踢

random.choice(moves[i])

相关问题 更多 >