【问题标题】:How to return the length of each element in a list using the Len() function?如何使用 Len() 函数返回列表中每个元素的长度?
【发布时间】:2013-09-29 15:46:06
【问题描述】:

问题:

写一个遍历的循环:

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

【问题讨论】:

  • 1 的长度应该是多少?那么1323 呢?对于您当前的输入,您的预期输出是什么?
  • 不要使用list作为变量名,否则可能会遇到更多错误。

标签: python string-length


【解决方案1】:

正如其他人所指出的,数字 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"

【讨论】:

    【解决方案2】:

    首先,使用该元素变量作为访问列表项的索引是多余的。在 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))
    

    【讨论】:

      【解决方案3】:

      我在考虑你的问题,我想你可能和我一样是 Python 的新手,对我来说一切都在 R 中解决了。我找到的解决方案是将列表中的所有元素设置为一个列表... 'element' 所以最后的代码可以遍历列表中的所有列表:

      for k in range(len(items)):
          if type(items[k])!= list:
             items[k]=[items[k]]
      items
      
      [len(i) for i in items]
      >>[1, 1, 3, 3]
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          可以使用 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
          

          【讨论】:

            猜你喜欢
            • 2015-12-02
            • 2014-12-29
            • 1970-01-01
            • 2017-06-23
            • 1970-01-01
            • 1970-01-01
            • 2013-12-10
            • 2022-01-05
            • 2015-01-31
            相关资源
            最近更新 更多