【问题标题】:What is happening with my types, TypeError? (Python)我的类型 TypeError 发生了什么? (Python)
【发布时间】:2015-04-16 15:45:34
【问题描述】:

我有一种方法可以从 SQLite 数据库中检索数据。数据保存为文本(出于某种原因),但实际上它是浮点数(14.5 等)。这是我获取它们的方法:

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]
        return speeds

这将返回以下内容:

[u'14.00', u'14.50', u'14.50', u'14.50', u'14.50', u'13.80']

但是,因为我想要纯数字,所以我这样做:

for i in range(0, len(speed)):
     newspeeds.append(float(speed[i]))

所以现在新的回报看起来像:

[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 len(speed>0):
    TypeError: object of type 'bool' has no len()

布尔?我非常困惑为什么我返回的列表现在是一个布尔值。

【问题讨论】:

  • 您不应该使用rangelen 进行迭代。就像你最初对列表理解所做的那样:speeds = [float(x[0]) for x in cur]

标签: python


【解决方案1】:

错误消息说你写了if len(speed>0):(注意>0len中),而不是len(speed)>0,因为你应该写它(就像你在代码sn-p中所做的那样)。

【讨论】:

    【解决方案2】:

    看,你打错了,正确的方法是if len(speed)>0:。你自己纠正了。

    len(5>2) 也不起作用,因为 5>2 返回 True 并且 True 没有 len()

    【讨论】:

      猜你喜欢
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      相关资源
      最近更新 更多