TypeError:+;的操作数类型不受支持:';浮动';和';列表';在Python 3.6.8中

TypeError:+;的操作数类型不受支持:';浮动';和';列表';在Python 3.6.8中,python,floating-point,python-3.6,typeerror,operands,Python,Floating Point,Python 3.6,Typeerror,Operands,我一直在获取TypeError:不支持+:“float”和“list”的操作数类型 我是python编程新手,正在尝试将Matlab代码转换为python。下面是试用过的python代码 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

我一直在获取
TypeError:不支持+:“float”和“list”的操作数类型

我是python编程新手,正在尝试将Matlab代码转换为python。下面是试用过的python代码

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 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'
pha的预期输出是一个介于1和286之间的数字数组/列表,即
[-940.7325,-729.3720,…,6.6187*e4,6.6449*e4]


我感谢所有能得到的帮助。非常感谢。

有多个问题。在表达式
math.cos((w[n/2+1+[j]]]-wc)
中,您通过执行
[j]
将整数
j
放在单个元素列表中。因此
[j]+任何_数
都不再起作用

此外,您正在为
ar
ter
编制索引,但它们是一个数字(请参阅)。如果您需要特定大小的数组/向量,可以与
size
参数一起使用

以下各项应该可以工作,但在每个循环迭代中使用相同的随机值
ar
ter

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)

你能修正
循环的缩进,并添加你的导入语句吗?此外
w(n/2+1+j)
会在Matlab中索引
w
,但在Python中你需要
[]
为numpy数组编制索引。@rinkert正如您所建议的,我在代码中做了一些更改,如导入语句、for循环缩进和w添加了[]。我希望这些是您的意思。我尝试了您的解决方案,但出现了此错误。您能帮我解决吗?pha=pha+ar*math.cos((w[n/2+1+j]-wc)*td+ter)索引器:只有整数、片(
)、省略号(
)、numpy.newaxis(
None
)和整数或布尔数组是有效的索引。表达式
w[n/2+1+j]是什么
计算到?只需将其放在给出错误的行的前面并打印出来。这就是问题所在。我没有得到任何输出。part=w[n/2+1+j]索引器:仅整数、切片(
)、省略号(
)、numpy.newaxis(
)整数或布尔数组是有效的指示符抱歉,我的意思是
n/2+1+j
。我从155.0156.0157.0158.0159.0160.0161.0162.0155.0,…162.0155.0,…162.0155.0,…162.0155.0中得到了四倍相同的浮点值