调用嵌套中的多个列表

时间:2018-01-18 23:52:31

标签: python list

import random

numlist = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[], [],[],[],[]]

for i in range(0, 7):   
    numlist[0:24].append(random.randint(0,100))

print(numlist)

0:24不起作用,我不想再为1-25列表重复该行。也许有一些非常简单的方法可以做到这一点,我一直在想,但到目前为止我找不到任何东西。我一次只能呼叫一个列表的一部分。

3 个答案:

答案 0 :(得分:4)

看起来您正在尝试创建0到100(含)之间的随机整数列表。您可以通过理解更轻松地完成此任务:

>>> [[random.randint(0, 100) for col in range(7)] for row in range(24)]
[[73, 21, 8, 89, 90, 63, 34],
 [29, 8, 76, 78, 74, 30, 59],
 [50, 96, 68, 88, 94, 85, 100],
 [37, 1, 28, 55, 70, 65, 65],
 [89, 2, 25, 100, 54, 63, 57],
 [48, 28, 43, 35, 9, 2, 37],
 [14, 14, 51, 30, 52, 43, 46],
 [81, 52, 41, 94, 8, 48, 50],
 [72, 12, 100, 27, 17, 19, 62],
 [46, 3, 71, 12, 21, 23, 42],
 [34, 1, 36, 100, 95, 0, 37],
 [99, 58, 21, 72, 4, 55, 85],
 [45, 30, 60, 94, 25, 14, 36],
 [19, 91, 68, 82, 89, 61, 47],
 [10, 10, 82, 77, 27, 61, 14],
 [60, 6, 6, 58, 17, 8, 46],
 [16, 42, 100, 10, 4, 15, 81],
 [9, 73, 28, 11, 54, 4, 46],
 [11, 75, 56, 93, 61, 15, 84],
 [22, 88, 0, 2, 76, 59, 56],
 [6, 75, 99, 35, 44, 65, 28],
 [89, 67, 60, 84, 44, 20, 30],
 [24, 71, 97, 5, 4, 49, 9],
 [7, 73, 77, 21, 50, 62, 52]]

如果你有可用的numpy,有一个更好的选择:

>>> import numpy as np
>>> np.random.randint(low=0, high=101, size=(24,7)).tolist()
[[96, 27, 39, 21, 39, 67, 56],
 [87, 77, 59, 93, 8, 2, 12],
 [28, 86, 80, 27, 95, 94, 55],
 [0, 85, 99, 94, 5, 30, 36],
 [90, 22, 12, 12, 95, 1, 24],
 [37, 52, 72, 27, 62, 13, 92],
 [51, 55, 78, 7, 33, 33, 94],
 [53, 88, 19, 11, 8, 66, 45],
 [14, 18, 72, 64, 26, 32, 41],
 [81, 79, 32, 65, 76, 25, 74],
 [1, 4, 89, 25, 13, 24, 55],
 [13, 95, 52, 95, 18, 78, 69],
 [95, 40, 71, 69, 13, 78, 48],
 [69, 98, 85, 64, 0, 97, 61],
 [53, 81, 64, 3, 2, 0, 78],
 [75, 79, 50, 69, 60, 32, 24],
 [60, 33, 45, 36, 99, 11, 16],
 [25, 13, 97, 47, 33, 53, 46],
 [6, 94, 53, 52, 55, 12, 30],
 [5, 24, 92, 90, 31, 4, 26],
 [1, 42, 89, 44, 86, 83, 1],
 [31, 52, 53, 19, 38, 52, 5],
 [47, 18, 14, 31, 49, 70, 69],
 [66, 9, 2, 10, 24, 24, 1]]

答案 1 :(得分:2)

这适用于随机列表,可满足您的需求。

yourlist = []
randomlist = []
for i in range(amount of lists):
    for numb in range(amout of random numbers):
        yourlist.append(random.randint(0,100))
    randomlist.append(yourlist)
    yourlist = []    

答案 2 :(得分:2)

正如其他答案中所提到的那样,列表理解绝对是走到这里的方式,但我想我会清除你原来尝试的一些问题:

numlist = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[], [],
[],[],[]]

for i in range(0, 7):   
    numlist[0:24].append(random.randint(0,100))

numlist[0:24]做的是返回一个列表,它是numlist从索引0到索引23的副本(包括第一个值,但不包括第二个值) )。然后.append正在处理这个新副本,为你的新数组添加一个随机整数,现在看起来像:

[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[], [],
[],[],[],14]

然后这个新副本没有被分配给任何变量,所以它只是被扔掉了,而且每次运行都会发生这种情况。

要将函数实际应用于集合中的每个值,您需要执行以下操作:

def append_random_num(lst):
    lst.append(random.randint(0,100))

for i in range(7): 
    map(append_random_num, numlist)

map函数将依次调用在列表的每个元素上传递的函数,在这种情况下访问内部列表并为每个元素附加值