[Tutor] Operators on complex numbers, and applying real to a list of real and complex numbers
spmcinerney at hotmail.com
Fri Sep 19 11:43:52 CEST 2008
Two questions about complex numbers:
a) why are methods __add__,__mul__ defined but not the operators '+','-','*','/' ?
How can I bind the methods to the obvious operators (without creating a custom
subclass of complex?) It seems pretty weird writing a.__add__(b)
b) Say I have a list ll which mixes real (float) and complex numbers.
ll = [1, 0.80-0.58j, 0.11+.2j]
What is the best Python idiom for getting the list of real parts of elements of ll?
[lx.real for lx in ll] fails because only complex numbers have a 'real'
attribute, real numbers don't (slightly bizarre).
Unless I write the not-so-readable:
[(type(lx) is complex and lx.real or lx) for lx in ll]
or define my own function.
Do any of you see a need for a math.real() (or math.complex())
function, which operates on all numeric types?
Then I could simply take the list comprehension
[real(lx) for lx in ll]
Is this worthy of a PEP?
It seems simple but overlooked.
See how Windows connects the people, information, and fun that are part of your life.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor