python - 我应该为 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
解决方案
我不确定为什么以下代码不会产生预期的结果,因为当我运行时:
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]))
推荐阅读
- c - 我怎样才能获得指向 $esp 或 $eip 的指针,以便利用 House of force 攻击?
- django - 创建django后将数据保存到另一个表
- reactjs - 在 Const 中将 props 从父级传递给组件
- javascript - javascript-“您不能在空值表达式上调用方法”;CategoryInfo: InvalidOperation: (:) [],
- sql-server - 检查两个表中是否存在字符串
- javascript - 仅当另一个函数在纯 JavaScript 中完成时才触发函数?
- css - Safari 中不支持溢出-x
- javascript - 使用 nodejs 向 xml 添加注释
- swift - 当我关闭 Onboarding 并第二次运行应用程序时出现 AppDelegate 问题
- android - Android分页库根本没有被解雇