为什么我会遇到类型错误:当我尝试迭代列表时浮动

时间:2015-04-16 17:24:21

标签: python

所以我在这里解决了我稍微有点尴尬的错误:What is happening with my types, TypeError? (Python)

现在我又得到了另一个。

我的检索数据的方法:

def retrieveSpeeds(databasepath, someid):
     con = lite.connect(databasepath)
     with con:
        cur = con.execute("SELECT speed FROM speeds WHERE id = someid")
        speeds = [x[0] for x in cur]
        for i in range(0, len(speed)):
            newspeeds.append(float(speed[i]))
     return speeds

所以回报如下:

[14.0, 14.5, 14.5, 14.5, 14.5, 13.8]

在我的主要内容中:

maxspeeds = []
for id in userid:
    speed = retrieveSpeeds(databasepath, id)
    if len(speed)>0:
           maxspeeds.append(max(speed))
for i in range(0,len(maxspeeds)):
    if maxspeeds[i] > 40:
          maxspeeds = maxspeeds.pop(i)

现在我的新问题是:

    Traceback (most recent call last):
    if maxspeeds[i]>40:
    TypeError: 'float' object has no attribute '__getitem__'

它突然认为我的列表是浮动对象怎么样?来自我的更多错误?

2 个答案:

答案 0 :(得分:4)

您要将maxspeeds分配给maxspeeds.pop(i)的输出,该输出会返回数字,这是pop ped项的索引。相反,不要为输出分配任何内容:

maxspeeds = []
for id in userid:
    speed = retrieveSpeeds(databasepath, id)
    if len(speed)>0:
           maxspeeds.append(max(speed))
for i in range(0,len(maxspeeds)):
    if maxspeeds[i] > 40:
          maxspeeds.pop(i) #Here

.pop返回已删除项目的索引,因此当您将列表分配给该输出时,列表将成为索引(整数)。

答案 1 :(得分:3)

这一行:

maxspeeds = maxspeeds.pop(i)

maxspeeds重新绑定到表达式maxspeeds.pop(i)的值,这是一个浮点数。