首页 > 解决方案 > 查找由 list 和 int 组成的子列表的列表长度

问题描述

根据标题,如何查找由 list 和 int 组成的子列表的列表长度。例如,给出一个列表

ListNo=[[6,2,5],[3,10],4,1]

它应该返回 LengthSubList 3,2,1,1。

我制作以下代码,

LengthSubList=[len(x) for x in ListNo]

但是,编译器给出以下错误

object of type 'int' has no len()

我可以知道我做错了什么吗?

提前致谢

标签: pythoncompiler-errorsvariable-length

解决方案


在你做之前检查它是否是一个列表len()

ListNo = [[6,2,5],[3,10],4,1]

print([len(x) if isinstance(x, list) else 1 for x in ListNo])
# [3, 2, 1, 1]

你错了,你不能做len(4)and len(1),仅仅因为它会返回一个TypeError- 'int' 类型的对象没有 len()。


推荐阅读