问题是:
Write a loop that traverses:
['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
and prints the length of each element.
我试过作为我的解决方案:
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()
首先,使用该元素变量作为访问列表项的索引是多余的。在python中编写for循环时,您将遍历列表中的每个项,以便在迭代1中:
在下一次迭代中: 对于[1,[1,2,3]]中的项: #项目=[1,2,3] ...
下一个问题是列表中有一个没有定义长度的项。我不知道你想用它做什么,但一个可能的解决方案是,如果项目是整数,它将打印项目的长度(以数字表示):
正如其他人指出的,数字1(主列表的第二个条目)没有定义的长度。但是,如果是这样的情况,您仍然可以捕获异常并打印出一些内容
唯一可能的解决方案是将
int
类型更改为str
,反之亦然。 如果只是一个练习,那就不成问题了。相关问题 更多 >
编程相关推荐