2014-01-21 55 views
2

我知道Python有cmath模塊來查找負數的平方根。負數組的平方根Python

我想知道的是,如何爲100個負數的數組做同樣的事情?

+0

迭代通過數組查找每個平方根?就像你會做一個非負數組一樣?對不起,如果我誤解了你的問題。 – gravetii

+1

'array'你的意思是'list'嗎? – DSM

+7

'map(cmath.sqrt,your_array)'? –

回答

4

你要遍歷一個列表的元素,並在其上應用sqrt功能,所以。您可以使用built-in function map,將第一個參數應用到第二的每一個元素:

lst = [-1, 3, -8] 
results = map(cmath.sqrt, lst) 

另一種方法是採用經典的列表理解:

lst = [-1, 3, -8] 
results = [cmath.sqrt(x) for x in lst] 

執行例如:

>>> lst = [-4, 3, -8, -9] 
>>> map(cmath.sqrt, lst) 
[2j, (1.7320508075688772+0j), 2.8284271247461903j, 3j] 
>>> [cmath.sqrt(x) for x in lst] 
[2j, (1.7320508075688772+0j), 2.8284271247461903j, 3j] 

如果您使用的是Python 3,則可能必須對地圖結果應用list()(或者您將擁有一個ietrator對象)

+0

或者這可以寫成一個列表解析:'[cmath.sqrt(x)for x in]' – Max

+1

另請注意,在python 3.x map '返回一個* map對象*,所以把它變成一個列表,你需要'list(map(cmath.sqrt,lst))' – SethMMorton

3
import cmath, random 

arr = [random.randint(-100, -1) for _ in range(10)] 
sqrt_arr = [cmath.sqrt(i) for i in arr] 
print(list(zip(arr, sqrt_arr))) 

結果:

[(-43, 6.557438524302j), (-80, 8.94427190999916j), (-15, 3.872983346207417j), (-1, 1j), (-60, 7.745966692414834j), (-29, 5.385164807134504j), (-2, 1.4142135623730951j), (-49, 7j), (-25, 5j), (-45, 6.708203932499369j)] 
3

如果速度是一個問題,你可以使用numpy的:

import numpy as np 
a = np.array([-1+0j, -4, -9]) 
np.sqrt(a) 
# or: 
a**0.5 

結果:

array([ 0.+1.j, 0.+2.j, 0.+3.j])