首页 > 解决方案 > 我应该为 numpy 数组添加哪些函数以考虑另一个 numpy 数组是包含单个元素还是多个元素?

问题描述

我在下面有以下代码

 populations = numpy.array([[random.randint(0, 1) for x in range(len(q_active))] for y in range(4)])

我想知道,我应该在上面的代码中添加什么,以便可以考虑其中是否q_active有一个或多个元素

截至目前,当我运行代码时,出现此错误:

populations = numpy.array([[random.randint(0, 1) for x in range(len(q_active))] for y in range(4)])
TypeError: len() of unsized object

标签: python

解决方案


我不确定为什么以下代码不会产生预期的结果,因为当我运行时:

import numpy as np
import random

q_active = [8]

populations = np.array([[random.randint(0, 1) for x in range(len(q_active))] for y in range(4)])

print(populations)

输出:

[[1]
 [1]
 [1]
 [0]]
  • 其中 0 和 1 是随机的

但是,如果它仍然不适合您,请尝试其他方法:

import numpy as np

q_active = [8]

populations = np.random.randint(0, 2, size=(4, len(q_active)))

print(populations)

输出:

[[1]
 [0]
 [1]
 [1]]
  • 其中 0 和 1 是随机的

如果仍然不起作用,请尝试:

populations = np.random.randint(0, 2, (4, q_active.shape[0]))

推荐阅读