Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 与randint一起使用for循环_Python - Fatal编程技术网

Python 与randint一起使用for循环

Python 与randint一起使用for循环,python,Python,使用此代码: from random import randint ans = [[randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20)] for i in range(15)] print (ans) 我明白了: [[10, 10, 13, 3, 13, 17, 3], [4, 1, 0, 15, 3, 9, 12], [8, 14, 8

使用此代码:

from random import randint
ans = [[randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20),randint(0, 20)] for i in range(15)]
print (ans)
我明白了:

[[10, 10, 13, 3, 13, 17, 3], [4, 1, 0, 15, 3, 9, 12], [8, 14, 8, 14, 2, 1, 11], [6, 13, 8, 9, 16, 18, 18], [10, 2, 15, 18, 16, 5, 4], [16, 3, 16, 9, 8, 20, 9], [1, 8, 16, 4, 7, 17, 20], [5, 0, 3, 11, 11, 3, 5], [17, 5, 14, 7, 20, 17, 17], [7, 4, 9, 17, 13, 0, 11], [3, 12, 6, 20, 9, 0, 3], [9, 12, 14, 16, 11, 4, 4], [12, 19, 12, 12, 11, 16, 12], [13, 15, 2, 3, 9, 17, 11], [14, 6, 10, 18, 8, 6, 6]]

但是正如你所看到的,randint0,20的重复并不好。你能帮我用一些别的东西,比如for循环,而不是重复相同的randint0,20吗?

你可以做一个双列表理解

from random import randint
ans = [[randint(0, 20) for j in range(7)] for i in range(15)]
print (ans)

为什么不是另一个列表理解?你能解释一下你在寻找什么,问题是什么吗?你考虑过使用NumPy吗?如果您想要二维列表,您可能更喜欢二维NumPy数组。NumPy的内置函数可以生成这样的随机数组。你可以看到,如果我想要一个包含20个元素的列表,我必须重复randint0,20次,我只是想避免这种情况……我的老师不想让我使用NumPy的:/正是我想要的。