【问题标题】:Integer/Float Typeerror in PythonPython中的整数/浮点类型错误
【发布时间】:2015-01-05 07:38:57
【问题描述】:

我正在尝试根据获取数据的日期(或纪元)将数据文件分成列表。我试图通过告诉程序如果一个点的纪元与前一点相同,则将其添加到列表中,如果不是则继续。我目前收到错误:

第 31 行,

    if epoch[i] == epoch[i+1]:
TypeError: list indices must be integers, not float

这就是我目前所拥有的(我还没有写到告诉它进入下一个时代)。

epoch=[]
wavelength=[]
flux=[]


text_file = open("datafile.dat", "r")
lines1 = text_file.read()
#print lines1
text_file.close()

a = [float(x) for x in lines1.split()]

a1=0
a2=1
a3=2

while a1<len(a):
    epoch.append(float(a[a1]))
    wavelength.append(float(a[a2]))
    flux.append(float(a[a3]))
    a1+=3                                                               
    a2+=3
    a3+=3

#print epoch
x=[]
y=[]
z=[]

i = epoch[0]
if epoch[i] == epoch[i+1]:
    x.append(epoch[i])
    y.append(wavelength[i])
    z.append(flux[i])
    i+=1
    #print x
    #print z

我不知道我需要改变什么!提前致谢。

【问题讨论】:

  • 尝试将 i 转换为 int > if epoch[int(i)] == epoch[int(i)+1]:

标签: python floating-point int typeerror


【解决方案1】:

你用这一行在列表中放了一个浮点数 - Python 不能使用这些作为索引,因为它们不是确定的值:

epoch.append(float(a[a1]))

该错误会告诉您您需要知道的一切。只需将i 转换为int:

i = int(epoch[0])

【讨论】:

    【解决方案2】:

    这一行将epoch 中的值存储为浮点数:

    epoch.append(float(a[a1]))
    

    然后你尝试使用epoch的第一个值访问epoch:

    i = epoch[0]
    if epoch[i] == epoch[i+1]:
    

    错误告诉您不能使用float 作为索引来访问列表。因此,您需要将值作为int 存储在epoch 中,或者在将其用作索引之前转换为int。

    【讨论】:

      【解决方案3】:

      在这一行:

      epoch.append(float(a[a1]))
      

      在附加到列表纪元之前,您将所有项目转换为浮点数。

      所以你对索引 i 的初始化:

      i = epoch[0]
      

      将始终包含不允许作为索引的浮点数(2.5 作为索引没有意义)。

      您需要做的,只是将您的索引 i 转换为整数:

      i = int(epoch[0])
      

      【讨论】:

        【解决方案4】:

        替换:

        i = epoch[0]
        

        作者:

        i = 0
        

        【讨论】:

          猜你喜欢
          • 2018-06-16
          • 1970-01-01
          • 1970-01-01
          • 2021-06-15
          • 2018-06-07
          • 2018-01-11
          • 1970-01-01
          • 1970-01-01
          • 2016-10-25
          相关资源
          最近更新 更多