如何重复以下示例序列:
l = np.array([3,4,5,6,7])
最多n
次,每次重复的值加倍。因此,对于n=3
:
[3, 4, 5, 6, 7, 6, 8, 10, 12, 14, 12, 16, 20, 24, 28]
也许有一种简单的方法来避免与numpy
产生循环吗?
答案 0 :(得分:10)
numpy.outer
+ numpy.ndarray.ravel
:
>>> a = np.array([3,4,5,6,7])
>>> n = 3
>>> factors = 2**np.arange(n)
>>> np.outer(factors, a).ravel()
array([ 3, 4, 5, 6, 7, 6, 8, 10, 12, 14, 12, 16, 20, 24, 28])
详细信息:
>>> factors
array([1, 2, 4])
>>> np.outer(factors, a)
array([[ 3, 4, 5, 6, 7], # 1*a
[ 6, 8, 10, 12, 14], # 2*a
[12, 16, 20, 24, 28]]) # 4*a
答案 1 :(得分:2)
您可以使用2的幂作为乘法因子来使用级联和列表理解。这里的<!DOCTYPE html>
<html>
<body>
<p id="id-of-element">This text will be replaced</p>
</body>
</html>
是您需要的重复次数。
3
答案 2 :(得分:1)
这是一种方法:
l = np.array([3,4,5,6,7])
final = np.concatenate([l*2**(i) for i in range(3)])
print (final)
array([ 3, 4, 5, 6, 7, 6, 8, 10, 12, 14, 12, 16, 20, 24, 28])
(仅在需要输入倍数的情况下有效。)
答案 3 :(得分:1)
您可以这样做:
import numpy as np
l = np.array([3, 4, 5, 6, 7])
rows = np.tile(l, 3).reshape(-1, len(l)) * np.power(2, np.arange(3)).reshape(-1, 1)
print(rows.flatten())
输出
[ 3 4 5 6 7 6 8 10 12 14 12 16 20 24 28]
答案 4 :(得分:1)
A = np.array([3,4,5,6,7])
res = (A * np.power(2, np.arange(3))[:, None]).ravel()
print(res)
array([ 3, 4, 5, 6, 7, 6, 8, 10, 12, 14, 12, 16, 20, 24, 28])
答案 5 :(得分:0)
您可以遍历n
,并每次连接一个新列表:
l = [3,4,5,6,7]
n = 3
new_l = []
for i in range(n):
new_l += [j*2**i for j in l]
new_l = np.array(new_l)
输出
array([3, 4, 5, 6, 7, 6, 8, 10, 12, 14, 12, 16, 20, 24, 28])
答案 6 :(得分:0)
您可以使用列表推导在纯python中做到这一点:
l = [3,4,5,6,7]
n = 3
mult = [1 * 2**i for i in range(n)]
final = list([x*m for m in mult for x in l])