【问题标题】:Output random numbers by line逐行输出随机数
【发布时间】:2019-02-06 12:09:48
【问题描述】:

好的,所以我编写了这个代码:

lst1 = tuple(range(1, 13))
table1 = ""
x = 0
while x < len(lst1):
    for y in range(0, 3):
        table1 += str(lst1[x]) + "\t"
        x += 1
    table1 += "\n"
print(table1)

#Output in console is:
1 2 3
4 5 6
7 8 9
10 11 12

我想再制作 2 个显示其他随机数的表格,即:从 0 到 48 可以说,但仍然只有该范围内的 12 个数字会以该格式输出。我对 python 还很陌生,似乎无法通过 random 模块弄清楚。

这是带有随机数的列表之一:

lst3 = tuple(range(0, 48))
table3 = ""
x = 0
while x < len(lst3):
    for y in range(0, 3):
        table3 += str(lst3[x]) + "\t"
        x += 1
    table3 += "\n"
print(random.sample(lst3, 12))

#Output is: (so basically just 12 random numbers from 1 to 47 that don't repeat)
[28, 15, 35, 11, 30, 20, 38, 3, 31, 42, 9, 24]

【问题讨论】:

    标签: python random numbers tabular


    【解决方案1】:

    据我了解,您想要这样的东西:

    import random
    
    lst1 = tuple(range(1, 13))
    lst2 = random.sample(range(0,48), 12) # increase this 12 as per your requirements
    table1 = ""
    table2 = ""
    x = 0
    while x < len(lst1):
        for y in range(0, 3):
            table1 += str(lst1[x]) + "\t"
            x += 1
        table1 += "\n"
    x = 0
    while x < len(lst2):
        for y in range(0, 3):
            table2 += str(lst2[x]) + "\t"
            x += 1
        table2 += "\n"
    
    print(table1)
    print (table2)
    

    【讨论】:

    • 是的!谢谢你,我试图弄清楚。感谢您向我展示它如何如此干净。 (至少从我的角度来看)
    猜你喜欢
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多