如何使用 Len() 函数返回列表中每个元素的长度?

新手上路,请多包涵

问题:

写一个遍历的循环:

>  ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
>
> ```
>
> 并打印每个元素的长度。

我试过作为我的解决方案:

list = [‘spam!’, 1,[‘Brie’, ‘Roquefort’, ‘Pol le Veq’], [1,2,3]] element = 0

for i in list: print len(list[element]) element += 1

”`

但它收到此错误: TypeError: object of type 'int' has no len()

原文由 BBedit 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 441
1 个回答

可以使用 map 和 __ len __ 来检查使用 len() 时是否会引发错误,例如

myList = ['spam!', 1,['Brie', 'Roquefort', 'Pol le Veq'], [1,2,3]]
myList_filter = list(filter(lambda x: hasattr(x, "__len__"), myList))
myList_len = list(map(len, myList_filter))
print(myList_len) # [5, 1, 3, 3]

error_type = [entry for entry in myList if entry not in myList_filter]
print("{0} has no defined length".format(error_type)) # [1] has no defined length

原文由 Albert.Huang 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏