首页 > 解决方案 > 如何从python中的条件列表中选择一个随机单词

问题描述

我是一名初级编码员,我想从我的列表中选择一个带有几个条件的随机元素,并且只有如果条件匹配,应该打印随机词,你能否建议一个可以在 python 3 中工作的代码。这里是代码

`import time
import random
wordbank = ["   the "   ,
"   of  "   ,
"   and "   ,
"   to  "   ,
"   a   "   ,
"   in  "   ,
"   that    "   ,
"   I   "   ,
"   was "   ,
"   he  "   ,
"   his "   ,
"   with    "   ,
"   is  "   ,
"   it  "   ,
"   for "   ,
"   as  "   ,
"   had "   ,
"   you "   ,
"   not "   ,
"   be  "   ,
"   on  "   ,
"   at  "   ,
"   by  "   ,
"   her "   ,
"   which   "   ,
"   have    "   ,
"   or  "   ,
"   from    "   ,
"   this    "   ,
"   but "   ]
print("hey this is the champion AI robot which no human can beat in 
playing word bank")
quasimodo = input("want to know how it is played y/n")
if quasimodo == "y" :
     print("so each player is going to start by saying a word and the 
other person is supposed to tell a word by the ending letter of the word 
and the loop continues untill one person cant tell a word in 20 secs")
print("lets play i mean how long can a human last in front of a computer")
print ("because of my kindness i will let you start prepare to lose")

    
while 7 < 8 :
    a = input()
    b = len(a)
    c = b + 1
    d = random.choice(wordbank)
    e = a[c]
    f = len(d)
    g = f + 1
    h = d[g]

标签: pythonpython-3.xlist

解决方案


import random

lst = ['a','b','c']
print(random.choice(lst))

(使用随机模块来获取随机值,而不是经历创建随机发生器的漫长过程)


推荐阅读