【问题标题】:Error when searching for the length of a list搜索列表长度时出错
【发布时间】:2019-09-06 19:01:30
【问题描述】:

[编辑:已解决,我从代码中的另一个位置调用相同的函数,输入参数错误,导致此错误]

我是 python 新手,经过一番搜索,我决定发布我的问题..

我的函数将 *args 作为输入:可变数量的列表

在此函数中,我使用 for 循环读取所有列表并尝试获取 len(each_list)。 然后我得到错误 TypeError: object of type 'numpy.float64' has no len()

我试图自己找出问题,但我不明白这种行为

如果我这样做:

def myfunction(* args):
    for p in args:
        print(isinstance(p, list))
        print(type(p))
        print(p)

我会得到:True + class 'list' + [value1, value2, ... etc]

但是如果我添加一行来获得长度(最后一行)

def myfunction(* args):
    for p in args:
        print(isinstance(p, list))
        print(type(p))
        print(p)
        a = len(p)

我会得到:False + class 'numpy.float64' + error(我知道它是不可迭代的)

我把函数称为:

All_lists = [list1, list2, list3]
myfunction(All_lists)
# I've also tried myfunction(*All_lists)

感谢您的帮助

【问题讨论】:

  • 那么list1list2list3 是什么?它们是numpy.float64 类型的吗?
  • list1, list2, list3 都是列表(长度相同)它们都包含:class 'numpy.float64' 所以总而言之我有:list[list[numpy.float64], list[numpy.float64], list[numpy.float64]] 并且函数得到(测试后):tuple[list[numpy.float64], list[numpy.float64], list[numpy.float64]]
  • 是的,编译器告诉您不能在numpy.float64 数组上使用len(),因此您必须为每个数组使用不同的函数或numpy.ndarray.size 属性或输入列表你可以使用len()len() 正在尝试计算所有列表中组合元素的数量。

标签: python-3.x


【解决方案1】:

参数列表的长度需要len(p)

def myfunction(* args):
    for p in args:
        print(isinstance(p, list))
        print(type(p))
        print(p)
        print(len(p))

myfunction([[1,2,3],[4,5,6],[7,8,9] ])
#True
#<class 'list'>
#[1, 2, 3]
#3

【讨论】:

    猜你喜欢
    • 2022-06-16
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2016-03-24
    相关资源
    最近更新 更多