我有一个数组a
。我想创建一个双倍大小的新数组,其中items是x * 2和x * 3.
例如:a = [1,10,100]
结果必须为b = [2,3,20,30,200,300]
我知道这种(丑陋且非常慢)的方式:b = sum([[x*2,x*3] for x in a], [])
还有其他方式(我真的想要最短的方式:)?
答案 0 :(得分:3)
这可以使用嵌套循环的列表推导来完成
In [4]: [y for x in a for y in (x * 2, x * 3)]
Out[4]: [2, 3, 20, 30, 200, 300]
似乎优于所有答案,但在numpy
较大时会失去a
解决方案。
答案 1 :(得分:2)
您可以在列表推导中执行乘法,然后zip
并展平结果列表。
>>> a = [1,10,100]
>>> b = [j for i in zip([i*2 for i in a], [i*3 for i in a]) for j in i]
>>> b
[2, 3, 20, 30, 200, 300]
答案 2 :(得分:0)
你可以通过以下几种方式做到这一点。下面是其中之一,使用numpy(第4行):
In [1]: import numpy as np
In [2]: a = [1, 10, 100]
In [3]: %timeit sum([[x*2,x*3] for x in a], [])
1000000 loops, best of 3: 632 ns per loop
In [4]: %timeit x = np.array(a); np.array([x*2,x*3]).T.ravel()
100000 loops, best of 3: 3.25 µs per loop
你的方式更快!但这是因为a
很小。当它变得更大时,numpy变得更好。
In [5]: a = range(1000)
In [6]: %timeit sum([[x*2,x*3] for x in a], [])
100 loops, best of 3: 2.37 ms per loop
In [7]: %timeit x = np.array(a); np.array([x*2,x*3]).T.ravel()
10000 loops, best of 3: 39.6 µs per loop
@ CoryKramer上面给出的答案包含了timeit结果,这对于小型阵列来说速度最快,但对于大型阵列而言也会失败:
In [10]: a = [1, 10, 100]
In [11]: %timeit [j for i in zip([i*2 for i in a], [i*3 for i in a]) for j in i]
1000000 loops, best of 3: 853 ns per loop
In [12]: a = range(1000)
In [13]: %timeit [j for i in zip([i*2 for i in a], [i*3 for i in a]) for j in i]
1000 loops, best of 3: 252 µs per loop
答案 3 :(得分:0)
通常使用元组比列表更快:
>>> timeit.timeit("sum([[x*2,x*3] for x in (1,10,100)], [])", number=10000)
0.023060083389282227
>>> timeit.timeit("sum(((x*2,x*3) for x in (1,10,100)), ())", number=10000)
0.01667189598083496