【发布时间】:2016-01-21 19:28:10
【问题描述】:
我正在创建这个数组:
A=itertools.combinations(range(6),2)
我必须用 numpy 操作这个数组,比如:
A.reshape(..
如果维度是A高,则list(A)的命令太慢了。
如何将 itertools 数组“转换”为 numpy 数组?
更新 1: 我已经尝试过hpaulj的解决方案,在这种特定情况下会慢一点,有什么想法吗?
start=time.clock()
A=it.combinations(range(495),3)
A=np.array(list(A))
print A
stop=time.clock()
print stop-start
start=time.clock()
A=np.fromiter(it.chain(*it.combinations(range(495),3)),dtype=int).reshape (-1,3)
print A
stop=time.clock()
print stop-start
结果:
[[ 0 1 2]
[ 0 1 3]
[ 0 1 4]
...,
[491 492 494]
[491 493 494]
[492 493 494]]
10.323822
[[ 0 1 2]
[ 0 1 3]
[ 0 1 4]
...,
[491 492 494]
[491 493 494]
[492 493 494]]
12.289898
【问题讨论】:
-
您好,请问您的问题在哪里?
-
如何将 itertools 数组“转换”为 numpy 数组?
-
你确定不是“太慢”,因为组合的数量太大了吗?如果您尝试创建十亿个元素或其他东西,那总是需要一段时间。
itertools.combinations调用立即返回,因为它实际上并没有预先创建任何组合,它是一个生成器。