【问题标题】:How to chose a random word from a list with a condition in python [closed]如何从python中的条件列表中选择一个随机单词[关闭]
【发布时间】:2020-09-14 08:26:33
【问题描述】:

我是一名初级编码员,我想从我的列表中选择一个带有几个条件的随机元素,并且只有如果条件匹配,应该打印随机词,您能否建议一个适用于 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]

【问题讨论】:

  • 请提供一些示例输入及其所需的输出。由于您的问题只是文本,因此很难想象和构建您的查询及其解决方案。
  • 好的,我会添加一些代码,但它是巨大的
  • 如果可能,请尝试仅使用必要的代码来编辑您的问题,无论是对您的问题直接重要的内容

标签: python python-3.x list


【解决方案1】:
import random

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

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

【讨论】:

    【解决方案2】:

    然后从列表中随机选择一个可以使用的项目yourlist[random.randint(0, yourlist.length - 1)]

    然后你可以检查这个元素。

    随机documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 2015-01-26
      • 2016-12-24
      • 2016-02-16
      相关资源
      最近更新 更多