Python标准库内置函数complex介绍

WBOY
Release: 2016-06-06 11:21:11
Original
1134 people have browsed it

本函数可以使用参数real + imag*j方式创建一个复数。也可以转换一个字符串的数字为复数;或者转换一个数字为复数。如果第一个参数是字符串,第二个参数不用填写,会解释这个字符串且返回复数;不过,第二个参数不能输入字符串方式,否则会出错。real和imag参数可以输入数字,如果imag参数没有输入,默认它就是零值,这个函数就相当于int()或float()的功能。如果real和imag参数都输入零,这个函数就返回0j。有了这个函数,就可以很方便地把一个列表转换为复数的形式。

注意:当想从一个字符串的复数形式转换复数时,需要注意的是在字符串中间不能出现空格,比如写成complex(‘1+2j'),而不是写成complex(1 +2j'), 否则会返回ValueError异常。

例子:

代码如下:


#complex()

print(complex(1))
print(complex('2+1j'))
print(complex(2, 5))

l = [1, 3, 4, 5]
for i in l:
 print(complex(i, 5))

结果输出如下:

代码如下:


(1+0j)

(2+1j)

(2+5j)

(1+5j)

(3+5j)

(4+5j)

(5+5j)

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!