【发布时间】:2021-02-28 14:49:42
【问题描述】:
我正在尝试生成 5x5 列表,其中正好有 10 个放置在 2D 列表中的随机位置。
我想让其余的条目为零。我怎样才能做到?
import random
def randomNumbers():
mylist=[random.randint(0, 1) for _ in range(5)]
return mylist
【问题讨论】:
我正在尝试生成 5x5 列表,其中正好有 10 个放置在 2D 列表中的随机位置。
我想让其余的条目为零。我怎样才能做到?
import random
def randomNumbers():
mylist=[random.randint(0, 1) for _ in range(5)]
return mylist
【问题讨论】:
你可以这样做
from random import shuffle
def randomNumbers():
l=[1 for _ in range(10)]+[0 for _ in range(15)]
shuffle(l)
lst=[]
for i in range(0,25,5):
lst.append(l[i:i+5])
return lst
【讨论】:
一种方法是从一个用零填充的二维列表开始,然后选择十个不同的坐标插入一个:
from random import sample
width = 5
height = 5
sample_size = 10
assert sample_size <= width * height
matrix = [[0] * width for _ in range(height)]
for x, y in sample([(x, y) for x in range(width) for y in range(height)], k=sample_size):
matrix[y][x] = 1
for row in matrix:
print(row)
输出:
[0, 0, 0, 1, 1]
[1, 0, 0, 1, 0]
[0, 0, 1, 1, 1]
[1, 1, 1, 0, 0]
[0, 0, 0, 0, 0]
>>>
【讨论】:
试试这个(使用 NumPy):
def get_output(shape, n):
Z = np.zeros(shape)
while np.sum(Z)<n:
Z[np.random.randint(0,shape[0]),np.random.randint(0,shape[1])] = 1
return Z
get_output((5,5), 10)
array([[0., 0., 1., 1., 0.],
[1., 0., 1., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 1., 1., 1., 0.],
[0., 1., 0., 1., 0.]])
get_output((3,3), 2)
array([[1., 0., 0.],
[0., 0., 0.],
[1., 0., 0.]])
【讨论】:
对于矩阵工作,通常首选的解决方案是 numpy. Numpy 具有比二维列表灵活得多的数组数据类型。 但是,这是一种仅使用 Python 列表的可能解决方案:
import random
li = [[0] * 5 for _ in range(5)] # make 2D list of zeros
inds = random.sample(range(25), 10) # get 10 random linear indices
for ind in inds:
i, j = ind // 5, ind % 5 # convert the linear indices to 2D
li[i][j] = 1
【讨论】:
这是嵌套循环的算法,但我没有将矩阵保存在列表中,您可以自己尝试一下。
import random
for val in range(10):
for val1 in range(10):
print(random.randint(0, 1), end=' ')
print("\n")
【讨论】:
使用numpy的另一种解决方案如下:
import numpy as np
import random
N = 5
ones_N = 10
x = np.zeros((N,N))
indices = random.sample(range(N*N), ones_N)
x.ravel()[indices] = 1
您将二维数组转换为一维数组,然后将位置 indices 的值设置为 1。
indices 将是一个ones_N 元素数组,其中包含从range(N*N) 采样的值。
另一种选择是只打乱包含ones_N 1 的二维数组。
import numpy as np
N = 5
ones_N = 10
x = np.zeros((N,N))
x.ravel()[:ones_N] = 1
np.random.shuffle(x.ravel())
【讨论】:
这应该可行:
import numpy as np
shape_1d = 5
shape_2d = 5
number_element = shape_1d * shape_2d
number_of_ones = 10
xx = np.zeros((number_element,1))
idx = np.random.choice(number_element, number_of_ones)
xx[idx] = 1
xx = xx.reshape((shape_1d, shape_2d))
xx = xx.tolist()
【讨论】:
先用 0 和 1 制作一维列表,使用random.sample 随机分配 1,而不用两次选择相同的索引:
from random import sample
pos_of_ones = sample(range(25), 10)
list_1D = [1 if i in pos_of_ones else 0 for i in range(25)]
那么要制作这个 2D,有两个选择:
result = np.array(list_1D).reshape(5, 5)
result = []
for i in range(0, 25, 5):
result.append(list_1D[i:i+5])
【讨论】:
从随机导入randint
y=[]
for p in range(0, 20): #list 的长度为 20
y.append([randint(0, 20),randint(50, 90)]) #1st list will have random numbers from 0 to 20 and 2nd list will have numbers from 50 to 90
【讨论】: