创建带有随机数的2D数组的简单方法(Python) [英] Simple way of creating a 2D array with random numbers (Python)
问题描述
我知道在Python中创建一个由零组成的NxN数组的简单方法是:
I know that an easy way to create a NxN array full of zeroes in Python is with:
[[0]*N for x in range(N)]
但是,让我们假设我想通过用随机数填充数组来创建该数组:
However, let's suppose I want to create the array by filling it with random numbers:
[[random.random()]*N for x in range(N)]
这不起作用,因为创建的每个随机数都会被复制N次,因此我的数组没有NxN个唯一的随机数.
This doesn't work because each random number that is created is then replicated N times, so my array doesn't have NxN unique random numbers.
是否可以在不使用for循环的情况下单行执行此操作?
Is there a way of doing this in a single line, without using for loops?
推荐答案
您可以使用嵌套列表理解:
You could use a nested list comprehension:
>>> N = 5
>>> import random
>>> [[random.random() for i in range(N)] for j in range(N)]
[[0.9520388778975947, 0.29456222450756675, 0.33025941906885714, 0.6154639550493386, 0.11409250305307261], [0.6149070141685593, 0.3579148659939374, 0.031188652624532298, 0.4607597656919963, 0.2523207155544883], [0.6372935479559158, 0.32063181293207754, 0.700897108426278, 0.822287873035571, 0.7721460935656276], [0.31035121801363097, 0.2691153671697625, 0.1185063432179293, 0.14822226436085928, 0.5490604341460457], [0.9650509333411779, 0.7795665950184245, 0.5778752066273084, 0.3868760955504583, 0.5364495147637446]]
或使用 numpy
(非stdlib,但非常流行):
Or use numpy
(non-stdlib but very popular):
>>> import numpy as np
>>> np.random.random((N,N))
array([[ 0.26045197, 0.66184973, 0.79957904, 0.82613958, 0.39644677],
[ 0.09284838, 0.59098542, 0.13045167, 0.06170584, 0.01265676],
[ 0.16456109, 0.87820099, 0.79891448, 0.02966868, 0.27810629],
[ 0.03037986, 0.31481138, 0.06477025, 0.37205248, 0.59648463],
[ 0.08084797, 0.10305354, 0.72488268, 0.30258304, 0.230913 ]])
(PS,这是一个好习惯,当您要表示 list
时要说出 list
并为numpy 保留
s.实际上有一个内置的 array
ndarray array
模块具有其自己的 array
类型,这样会使事情更加混乱,但是相对很少使用.)
(P.S. It's a good idea to get in the habit of saying list
when you mean list
and reserving array
for numpy ndarray
s. There's actually a built-in array
module with its own array
type, so that confuses things even more, but it's relatively seldom used.)
这篇关于创建带有随机数的2D数组的简单方法(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!