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

2024-10-05 15:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是:

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()


Tags: andoflelooplenthatelementspam
3条回答

首先,使用该元素变量作为访问列表项的索引是多余的。在python中编写for循环时,您将遍历列表中的每个项,以便在迭代1中:

for item in [1, [1,2,3]]:
    # item = 1
    ...

在下一次迭代中: 对于[1,[1,2,3]]中的项: #项目=[1,2,3] ...

下一个问题是列表中有一个没有定义长度的项。我不知道你想用它做什么,但一个可能的解决方案是,如果项目是整数,它将打印项目的长度(以数字表示):

items = ['spam!', 1,['Brie', 'Roquefort', 'Pol le Veq'], [1,2,3]]

for item in items:
    if isinstance(item, int):
        print(len(str(item)))
    else:
        print(len(item))

正如其他人指出的,数字1(主列表的第二个条目)没有定义的长度。但是,如果是这样的情况,您仍然可以捕获异常并打印出一些内容

myList = ['spam!', 1,['Brie', 'Roquefort', 'Pol le Veq'], [1,2,3]]

for entry in myList:
    try:
        l = len(entry)
        print "Length of", entry, "is", l
    except:
        print "Element", entry, "has no defined length"

唯一可能的解决方案是将int类型更改为str,反之亦然。 如果只是一个练习,那就不成问题了。

相关问题 更多 >