【发布时间】:2015-08-26 12:13:44
【问题描述】:
对于我的项目,我希望快速生成固定长度的二进制数组和给定数量的 1 和 0 的随机排列。鉴于这些随机排列,我希望按元素添加它们。
我目前使用的是numpy的ndarray对象,方便逐元素添加。我目前的代码如下:
# n is the length of the array. I want to run this across a range of
# n=100 to n=1000.
row = np.zeros(n)
# m_list is a given list of integers. I am iterating over many possible
# combinations of possible values for m in m_list. For example, m_list
# could equal [5, 100, 201], for n = 500.
for m in m_list:
row += np.random.permutation(np.concatenate([np.ones(m), np.zeros(n - m)]))
我的问题是,有没有更快的方法来做到这一点?根据 timeit,1000000 次调用“np.random.permutation(np.concatenate([np.ones(m), np.zeros(n - m)]))”需要 49.6 秒。出于我程序的目的,我想将其减少一个数量级。谁能建议一种更快的方法来做到这一点?
谢谢!
【问题讨论】:
-
只是好奇,
python -O?
标签: arrays numpy random binary permutation