【问题标题】:How do I print a single RANDOM item from multiple lists? and having those items print on the same line?如何从多个列表中打印单个 RANDOM 项目?并让这些项目打印在同一行?
【发布时间】:2017-09-24 17:45:54
【问题描述】:

我的原始代码:简化: (stackflow 新手,如果这是错误的做法,我深表歉意)

import random

count = 0
while count < 50:
    One = ['a', 'b', 'c', 'd', 'e']
    print(random.choice(One))

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

    Three =['a','b','c','d','e','f','g','h']
    print(random.choice(Three))

    Four =['a','b']
    print(random.choice(Four))
    count = count +1

我的代码输出在自己的行上打印每个项目.. 如果我要运行一次代码(没有 WHILE COUNT LOOP),输出将显示:

示例:(每次运行代码时随机,完美)

c

b

h

一个

多次:(随机顺序,非常适合我想要的)

d

一个

f

b

__

c

b

h

一个

等等……

问题: 我想要代码做的是,从每个列表中获取一个随机项目[一,二,三,四] ...并在其自己的行上打印这些随机项目并带有间距..所有同时使用WHILE COUNT LOOP(生成 n 个测试)

所以我想要它做的一个例子看起来像:

c a g b

b b f a

d a e b

假设我的列表有正确的名称和相关的值,会读取

输出:

狗翻了

一只鸟吃了种子

猫卷种子

汽车坐下

一条蛇咬了我

蜘蛛跑了

等等。

(其中一些没有意义,但那是我正在研究的“随机”想法

【问题讨论】:

    标签: python-3.x loops random while-loop count


    【解决方案1】:
    import random
    
    count = 0
    while count < 50:
        tmp = []
        for lst in [One, Two, Three, Four]:
            tmp.append(random.choice(lst))
        print(' '.join(lst))
        count = count +1
    

    【讨论】:

      【解决方案2】:

      你也可以使用:

      print(random.choice(One), end= " ")
      

      这一行应该“剪切”换行符

      【讨论】:

        猜你喜欢
        • 2022-08-13
        • 2016-03-06
        • 2022-08-15
        • 2014-08-19
        • 1970-01-01
        • 2017-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多