Python 负数组的平方根
我知道Python有cmath模块来查找负数的平方根 我想知道的是,如何对一个由100个负数组成的数组执行相同的操作Python 负数组的平方根,python,arrays,sqrt,cmath,Python,Arrays,Sqrt,Cmath,我知道Python有cmath模块来查找负数的平方根 我想知道的是,如何对一个由100个负数组成的数组执行相同的操作 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.9442719
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)]
您希望迭代列表中的元素,并对其应用
sqrt
函数。您可以使用,它将第一个参数应用于第二个的每个元素:
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,您可能必须在map的结果上应用
list()
(或者您将有一个ietter对象)如果速度是个问题,您可以使用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])
遍历数组以找到每个数组的平方根?就像对非负数组一样?抱歉,如果我误解了你的问题。
array
你的意思是list
?map(cmath.sqrt,你的_数组)
?@DSM By array,我的意思是一个包含100个数字的列表,或者可以写成一个列表理解:[cmath.sqrt(x)代表lst中的x]
还要注意,在python 3.xmap
上返回一个map对象,因此,要将其转换回列表,您需要list(map(cmath.sqrt,lst))