【问题标题】:I need to print this 20 times我需要打印 20 次
【发布时间】:2015-07-03 17:34:55
【问题描述】:

所以基本上我在这里有我的代码,它通过 3 个列表打印出随机的莎士比亚侮辱。要提交此代码,我必须打印 20 次侮辱,而且我知道有比编写 20 次最终打印语句更快的方法。这可能是补救措施,但我不记得该怎么做。这是我的代码谢谢大家:

import random

list1 = ["Artless", "Bawdy", "Bootless", "Churlish", "Clouted"]
list2 = ["Base-court", "Bat-fowling", "Beetle-headed", "Clay-brained" ]
list3 = ["Apple-john", "Baggage", "Bladder", "Boar-pig", "Coxcomb"]

def nurd1():
  return (random.choice(list1))

def nurd2():
   return (random.choice(list2))

def nurd3(): 
    return (random.choice(list3))

print ("Thou" + " " + nurd1() + " " +  nurd2() + " " + nurd3() )

【问题讨论】:

标签: python random


【解决方案1】:
import random

words = [
["Thou"],
["Artless", "Bawdy", "Bootless", "Churlish", "Clouted"],
["Base-court", "Bat-fowling", "Beetle-headed", "Clay-brained" ],
["Apple-john", "Baggage", "Bladder", "Boar-pig", "Coxcomb"]
]

print(*(' '.join([random.choice(l) for l in words]) for r in range(20)), sep='\n')

【讨论】:

    【解决方案2】:
    from random import choice
    list =[
     ["Artless", "Bawdy", "Bootless", "Churlish", "Clouted"],
     ["Base-court", "Bat-fowling", "Beetle-headed", "Clay-brained" ],
     ["Apple-john", "Baggage", "Bladder", "Boar-pig", "Coxcomb"]
    ]
    for i in range(20):
        print '\nThou ',
        for j in range(len(list)):
            print choice(list[j]),
    

    【讨论】:

    • 这是最基本的。我希望这会有所帮助
    • 这会隐藏内置列表类型。换行符不是必需的,我怀疑 OP 使用的是 Python 3.x,其中 print 是一个函数而不是语句。
    【解决方案3】:

    简单的while循环

    loop = 0
    
    while(loop <= 19):
        print ("Thou" + " " + nurd1() + " " +  nurd2() + " " + nurd3() )
        loop += 1
    

    虽然它会打印 20 行不同的行!

    【讨论】:

    • 我也想知道第一行的分号在那里做什么。
    • 啊哈哈哎呀,一分钟前正在做一些javascript,我的错!
    猜你喜欢
    • 2018-07-19
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2016-03-20
    • 2023-01-04
    相关资源
    最近更新 更多