Python - 使用随机值创建许多列表

时间:2014-12-13 20:06:14

标签: python list

我希望python中有许多(数百个)列表遵循以下形式:

[random.randint(1,100), random.randint(50, 100), random.randint(10,20), random.randint(1,100)]

我想将它们命名为list1,list2,list3等,一直到list500,list501等。

有没有办法自动化这一切?或者我不应该使用列表?

2 个答案:

答案 0 :(得分:1)

试试这个:

 my_lists = [[random.randint(1,100), random.randint(50, 100), random.randint(10,20), random.randint(1,100)] for x in range(500)]

演示5:

>>> my_lists [[random.randint(1,100), random.randint(50, 100), random.randint(10,20), random.randint(1,100)] for x in range(5)]
>>> my_lists
[[98, 58, 15, 63], [69, 59, 12, 37], [62, 58, 16, 7], [55, 97, 17, 55], [98, 53, 14, 90]]

答案 1 :(得分:0)

以下是一个简单的代码段,它会在dict中创建“命名”列表:

rand_lists = dict(('list{}'.format(i), [random.randint(1,100), random.randint(50, 100), random.randint(10,20), random.randint(1,100)]) for i in xrange(1,501))
rand_lists['list437']
>>> [3,52,12,90]