Home > Blockchain >  `TypeError: can't multiply sequence by non-int of type 'complex'` when convert float
`TypeError: can't multiply sequence by non-int of type 'complex'` when convert float

Time:02-17

Python script to convert float list to complex list as below:

data=[0.1455056963719547,3.068672071910097e-07,-1.50649354101907e-10,-0.07398991280122003]
complex_data=data[1::2]*1j
complex_data =data[0::2]

give me TypeError: can't multiply sequence by non-int of type 'complex'

Even,

print(1j*[0.1455056963719547,3.068672071910097e-07,-1.50649354101907e-10,-0.07398991280122003])
print(1j*[0.1455056963719547,3.06867207191009707,1.5064935410190710,0.07398991280122003])

has same error.

Where is the problem?

CodePudding user response:

If you are interested in a solution rather than the cause of the problem, I simply suggest you to use numpy such as what follows:

import numpy as np
data=[0.1455056963719547,3.068672071910097e-07,-1.50649354101907e-10,-0.07398991280122003]
data = np.array(data)
complex_data=data[1::2]*1j
complex_data =data[0::2]

CodePudding user response:

The syntax you are using is valid for numpy.ndarray but has a different meaning for list.

assert([1] * 4 == [1, 1, 1, 1])
>>>True

In essence if you multiply a list a by an integer n, it's producing a list made of n times the elements of a.

If you want to multiply all the elements of a list by a scalar, you can use a comprehension:

data = [0.1455056963719547,3.068672071910097e-07,-1.50649354101907e-10,-0.07398991280122003]
complex_data = [el * 1j for el in data[1::2]]
complex_data = [re   im for re, im in zip(data[0::2], complex_data)]

or more directly:

 complex_data = [re   im * 1j for re, im in zip(data[0::2], data[1::2])]
  • Related