【问题标题】:Python find size of each sublist in a listPython查找列表中每个子列表的大小
【发布时间】:2020-01-31 00:58:28
【问题描述】:

我有一个大的浮点数和整数列表,如下所示。我想通过忽略空元素或单个元素来查找每个子列表的长度。

big_list = [[137.83,81.80,198.56],0.0,[200.37,151.55,165.26, 211.84],
 0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]

我现在的密码:

list_len = []
for i in big_list: 
     list_len.append(len(i))

当前输出:

TypeError: object of type 'numpy.float64' has no len() 

预期输出:

list_len = [3,4,3,6,4,3] # list_len should neglect elements like 0, 4 in big_list. 

【问题讨论】:

  • 检查类型或捕获异常
  • "# list_len 应该忽略 big_list 中的 0、4 等元素" 听起来像是您需要在脚本中构建的一些逻辑
  • 这里的pandas有什么用?
  • @MadPhysicist 我只想考虑列表,而不是元素。我想忽略它们。

标签: python pandas numpy


【解决方案1】:

我会选择:

big_list = [(137.83,81.80,198.56),0.0,np.array([200.37,151.55,165.26, 211.84]),
 0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]

list_len = [len(x) for x in big_list if hasattr(x, '__len__') and len(x)>0]

也适用于 numpy 数组和元组

【讨论】:

    【解决方案2】:
    res = [len(l) for l in big_list if isinstance(l, list) and len(l)> 0]
    

    【讨论】:

      【解决方案3】:

      使用列表推导和列表类型检查,如下所示:

      big_list = [[137.83,81.80,198.56],0.0,[200.37,151.55,165.26, 211.84],
       0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]
      
      lengths = [
          len(sub_list) for sub_list in big_list if isinstance(sub_list, list)
      ]
      print(lengths)
      
      >>> [3, 4, 3, 6, 4, 3]
      

      【讨论】:

      • 这些可能是 NumPy 数组...除了isinstance(sub_list, list),您还可以检查hasattr(sub_list, '__len__') 之类的东西。
      • @jdehesa 这很聪明,你应该在另一个答案中添加它!
      【解决方案4】:
      list(map(len, filter(lambda x: isinstance(x, list), big_list)))
      

      【讨论】:

        【解决方案5】:

        您可以使用带有 if-else 语句的压缩列表:

        list_len = [len(x) for x in big_list if isinstance(x,list)]
        

        【讨论】:

        • 没有回答 0 len 列表的问题。
        猜你喜欢
        • 1970-01-01
        • 2023-01-02
        • 2022-07-22
        • 2020-10-03
        • 2016-12-21
        • 2011-08-31
        • 1970-01-01
        • 1970-01-01
        • 2011-11-26
        相关资源
        最近更新 更多