负数组Python的平方根

时间:2014-01-21 16:05:27

标签: python arrays sqrt cmath

我知道Python有cmath模块来查找负数的平方根。

我想知道的是,如何对100个负数的数组做同样的事情?

3 个答案:

答案 0 :(得分: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对象)

答案 1 :(得分: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)]

答案 2 :(得分: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])