我是Python的新手;但是,我想列出6个子列表,每个子列表包含0
和30
之间的4个随机值。
答案应该如下打印:
lst[0] = [1,4,4,5]
lst[1] = [23,14,5,8]
...
lst[5] = [8,9,18,27]
答案 0 :(得分:1)
这是一个简单的单行程,它将完成它:
from random import randint
rand_list = [[randint(0, 30) for i in range(4)] for n in range(6)]
>>>rand_list
[[28, 17, 5, 9],
[27, 29, 3, 8],
[18, 13, 4, 11],
[15, 12, 11, 19],
[17, 8, 22, 30],
[24, 6, 9, 1]]
如果你想获得幻想,你可以轻松地将它扩展为一个函数,允许你指定列表大小作为函数的输入:
def rand_lists(num_lists, num_vals):
return [[randint(0, 30) for i in range(num_vals)] for n in range(num_lists)]
>>> rand_lists(2, 7)
[[17, 8, 29, 2, 9, 26, 16],
[24, 22, 5, 10, 11, 0, 10]]
答案 1 :(得分:0)
对于单行:
from random import randint
lst = [[randint(0, 30) for col in range(4)] for row in range(6)]
这相当于(在纯python中):
lst = []
for row in range(6):
r = []
lst.append(r)
for col in range(4):
r.append(randint(0, 30))