数据类型定义-TypeError

时间:2018-10-24 20:10:29

标签: python

import cmath
import math
import random
import time

P = []
V = []
Vin = []

def Compute_wn_win(n,V,Vin):
    for i in range (0,n):
        V.append(complex(math.cos(2*math.pi*i/n),math.sin(2*math.pi*i/n)))
        Vin.append(1/(complex(math.cos(2*math.pi*i/n),math.sin(2*math.pi*i/n))))    

Compute_wn_win(8,V,Vin)

for i in range(0,8):
    random_number = random.uniform(-1.0,1.0)
    P.append(random_number)

def FFT(P,V,n):
    if(n==1):
        return P[0]
    else:
        Peven = []
        Podd = []
        for i in range(0,n/2):
            Peven.append(P[2*i])
            Podd.append(P[(2*i)+1])
        Vsquared = []
        for i in range(0,n/2):
            Vsquared.append(V[i]*V[i])
        Sole = FFT(Peven,Vsquared,n/2)
        Solo = FFT(Podd,Vsquared,n/2)
        Sol = [0 for x in range(0,n)]
        for i in range(0,n/2):
            Sol[i] = Sole[i]+V[i]*Solo[i]
            Sol[i+n/2] = Sole[i]-V[i]*Solo[i]
        return Sol
Sol = FFT(P,V,8)

我是Python的新手。我有以下代码。但是,对于行Sole = FFT(Peven,Vsquared,n/2)Sol[i] = Sole[i]+V[i]*Solo[i],我收到以下错误。但是,我将Sole,Solo和Sol定义为列表数据类型,所以我不明白为什么它提到float数据类型没有属性 getitem

确切错误是

Traceback (most recent call last):
  File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 40, in <module>
    Sol = FFT(P,V,8)
  File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 33, in FFT
    Sole = FFT(Peven,Vsquared,n//2)
  File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 33, in FFT
    Sole = FFT(Peven,Vsquared,n//2)
  File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 37, in FFT
    Sol[i] = Sole[i]+V[i]*Solo[i]
TypeError: 'float' object has no attribute '__getitem__'

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

SoleSolo是递归调用FFT()的返回值,但是FFT()的基本情况(当n == 1时)返回浮点数,而不是列表,因此通过尝试对浮点数进行索引,基本情况下的步骤将失败。大概您想将基本情况下的return P[0]更改为return [P[0]]