如何从多个列表中打印单个RANDOM项目?并将这些项目打印在同一行?

时间:2017-04-27 05:16:14

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

我的原始代码:简化: (对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),OUTPUT会显示:

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

C

B'/ P>

ħ

多次:(随机顺序,这是我想要的完美)

d

˚F

B'/ P>

__

C

B'/ P>

ħ

等...

问题: 我想要的代码是,从每个列表[1,2,3,4]中取一个随机项...然后使用spacing..all在自己的行上打印这些随机项在COUNT LOOP(生成n个测试)的时候

所以我想要它做的例子如下:

c a g b

b b f a

d a e b

假设我的列表具有正确的名称和关联值,请阅读

输出:

狗滚了过来

一只鸟吃了种子

猫滚了种子

汽车坐下了

一条蛇咬我

蜘蛛跑了

etc.etc。

(其中一些没有意义,但那就是&#34;随机&#34;想法我正在

工作

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您也可以使用:

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

此行应“剪切”新行字符