【问题标题】:Python: retrieving the length of a list of listsPython:检索列表列表的长度
【发布时间】:2013-12-13 00:26:24
【问题描述】:

在尝试检索列表列表的长度时,我收到以下错误:“TypeError: 'float' object is not callable”

我的代码如下所示:

list = []    
for line in text:
    regex = re.search("(.*) (.*) (.*)")
    a = float(regex.group(1))
    b = float(regex.group(2))
    c = float(regex.group(3))
    list.append([a, b, c])

newlist = []
for entry in list:
    if entry[0] < 10:
         newlist.append(entry)

if len(newlist) >1:
    do something

列表列表('newlist')的生成没有问题,例如[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]

而且绝对是一个列表,即type 'list'

但是当我尝试使用时:

len(list)

我刚刚收到 TypeError。我可能错过了一些非常明显的事情,但我看不出我做错了什么,有人可以帮忙吗?

谢谢你:)

【问题讨论】:

  • 不要使用list 作为变量名——它会影响内置函数。
  • 请保持提问者的代码不变。如果list 已被重用,则可能其他名称(包括len)已被隐藏。

标签: python typeerror


【解决方案1】:

问题不在于列表,而在于len。您可能使用名称 len 作为变量之一。这就是为什么你不能调用函数len,它被隐藏了。

lenliststrothers 是内置函数。您应该避免使用相同的名称命名变量。

【讨论】:

  • 你绝对的天才,非常感谢你,我觉得自己像个白痴! :D
  • 不客气!如果这对你有帮助,你可以accept the answer :)
  • 要在遇到“TypeError 对象不可调用”时添加@user3097536,很可能是您已经隐藏了内置的某些内容或使用本地变量名导入的内容。
【解决方案2】:

这个程序对我来说很好,检查你的输入格式

完整程序:

#!/usr/bin/python

import re

mylist = []
for line in ("0.1 0.2 0.3", "20 0.3 0.1", "0.2 0.1 5"):
    regex = re.search("(.*) (.*) (.*)", line)
    a = float(regex.group(1))
    b = float(regex.group(2))
    c = float(regex.group(3))
    mylist.append([a, b, c])

newlist = []
for entry in mylist:
    if entry[0] < 10:
         newlist.append(entry)

if len(newlist) > 1:
    print newlist

if len(mylist) > 1:
    print mylist

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2018-01-20
    • 1970-01-01
    相关资源
    最近更新 更多