TypeError: unsupported operand type(s) for +: 'float' and 'list' in Python 3.6.8

蹲街弑〆低调 提交于 2019-12-13 08:08:45

问题


I keep getting TypeError: unsupported operand type(s) for +: 'float' and 'list'.

I am new to python programming and am trying to convert Matlab code into Python. Below is the tried python code.

import math
import cmath
import numpy as np
import random

Tp = .1e-6         
Xc = 2.e3       
c = 3e8 
B0 = 100e6  
X0 = 50        
w0 = 2 * cmath.pi * B0
fc = 1e9       
wc = 2*cmath.pi * fc
alpha = w0 / Tp         
wcm = wc - alpha * Tp       
Ts = (2 * (Xc - X0)) / c    
Tf = (2 * (Xc - X0)) / c + Tp   
dt = cmath.pi / (2 * alpha * Tp)  
n = 2 * math.ceil((0.5 * (Tf - Ts)) / dt) 
t = Ts + np.arange(0, n*dt, dt) 

dw = 2*cmath.pi / (n * dt)                  
w = wc + dw * np.arange(-n/2,n/2)  
xn = [0, 35, 36.5, -25]            
fn = [1, 0.8, 1, 0.8]               

ntarget = 4

# SIMULATION

s = np.zeros((1,n))             
na = 8              
ar = random.uniform(1,na)              
ter = 2 * cmath.pi * random.uniform(1,na)         

for i in np.arange(ntarget): 
td = t - (2 * (Xc + xn[i]) / c)
pha = wcm * td + alpha * np.power(td, 2)        
for j in np.arange(na):               
    pha = pha + ar[j] * math.cos((w[n/2 + 1 + [j]] - wc) * td + ter[j])

print('pha :', pha)

Error message:

Error at
    pha = pha + ar[j] * math.cos((w[n/2 + 1 + [j]] - wc) * td + ter[j])

TypeError: unsupported operand type(s) for +: 'float' and 'list'

Expected output of pha is an array/list of numbers between 1 and 286, i.e [-940.7325, -729.3720,......,6.6187*e4,6.6449*e4]

I appreciate all the help I can get. Thanks a lot.


回答1:


There are multiple problems. In the expression math.cos((w[n/2 + 1 + [j]] - wc) you are putting the integer j in a single element list by doing [j]. Hence [j] + any_number does not work anymore.

Furthermore, you are indexing ar and ter, but these are one number (see random.uniform). If you want an array/vector of a specific size, you can use np.random.uniform with the size argument.

The following should work, but uses the same random values ar and ter on each loop iteration:

s = np.zeros((1,n))             
na = 8              
ar = random.uniform(1,na)              
ter = 2 * cmath.pi * random.uniform(1,na)         

for i in np.arange(ntarget): 
    td = t - (2 * (Xc + xn[i]) / c)
    pha = wcm * td + alpha * np.power(td, 2)        
    for j in np.arange(na):               
        pha = pha + ar * math.cos((w[n/2 + 1 + j] - wc) * td + ter)
        print('pha :', pha)


来源:https://stackoverflow.com/questions/57853113/typeerror-unsupported-operand-types-for-float-and-list-in-python-3-6-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!