python - 查找由 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()
我可以知道我做错了什么吗?
提前致谢
解决方案
在你做之前检查它是否是一个列表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()。
推荐阅读
- c++ - 设计用于制作形状的算法
- python-3.x - 三角形面积的面向对象Python
- java - SoundPool 媒体播放为铃声而不是媒体
- visual-studio - 当我遇到障碍物或坠地时尝试让游戏重新开始时出现错误
- flutter - 如何处理 TextEditorController
- hibernate - 使用spring data jpa(hibernate)批量加载和更新的有效方法
- android - 带有颤动的 Firebase 动态链接:深层链接 URL 未打开应用程序
- ios - StackView 中的 iOS UIButtons 没有被点击
- angular - Angular - 组件之间未传递服务数据
- c# - 有没有办法让我在没有窗口的情况下将图像绘制到我的屏幕上?