【问题标题】:length of list contents with lists inside列表内容的长度,里面有列表
【发布时间】:2018-07-10 11:32:03
【问题描述】:

是否有命令获取列表项的总数?

例子:

Names = [['Mark'], ['John', 'Mary'], ['Cindy', 'Tom'], ['Ben']]
print (len(Names))

输出

4

但我想要列表项的总数,所以结果是 6。我刚开始学习 python,所以放轻松。

【问题讨论】:

标签: python list count items


【解决方案1】:

您可以使用map 将函数应用于可迭代对象的每个元素。这里我们应用len函数和sum结果:

Names = [['Mark'], ['John', 'Mary'], ['Cindy', 'Tom'], ['Ben']]
print(sum(map(len, Names)))
# 6

只要Names 的每个元素实际上是list,这个(以及所有其他答案)才有效。如果其中一个是str,它将添加字符串的长度,如果它没有长度(如intfloat),它将引发TypeError

由于现代 Python 中有时不赞成函数式方法,因此您也可以使用 list comprehension(实际上是 generator comprehension):

print(sum(len(x) for x in Names))
# 6

【讨论】:

    【解决方案2】:
    Names = [['Mark'], ['John', 'Mary'], ['Cindy', 'Tom'], ['Ben']]
    
    no_of_names = 0
    
    for name_list in Names:
        if isinstance(name_list,list):
            no_of_names += len(name_list)
        elif isinstance(name_list,str):
            no_of_names += 1
    
    print(no_of_names)
    

    输出

    6
    

    【讨论】:

      【解决方案3】:
      from collections import Iterable
      
      names = [['Mark'], ['John', 'Mary'], ['Cindy', 'Tom'], ['Ben']]
      
      count = 0
      ignore_types = (str,bytes)
      
      for x in names:
          if isinstance(x, Iterable) and not isinstance(x, ignore_types):
              count += len(x)
          else:
              count += 1
      
      print(count)
      

      这将检查列表中的项目是否为可迭代对象,如列表或字符串。如果它是一个列表,那么 count 会增加列表的长度,如果项目在 ignore_types 中,则增加 1

      【讨论】:

        【解决方案4】:
        import time
        
        nameslen = 0
        
        """ There is a list named Names wich contains 4 lists, 0 = ["Mark]
                                                               1 = ['John', 'Mary']
                                                               2 = ['Cindy', 'Tom']
                                                               3 = ['Ben']
        """
        
        Names = [['Mark'], ['John', 'Mary'], ['Cindy', 'Tom'], ['Ben']]
        
        # using print (len(Names)) you will get as result 4, 
        # that means list Names contain 4 lists 
        
        
        for x in range(len(Names)):
            # for each list in Names lists
            # len the list values  
            nameslen += len(Names[x])
        
        print (nameslen)
        

        【讨论】:

        • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-19
        • 2018-01-20
        • 2014-12-09
        • 1970-01-01
        • 2018-03-19
        相关资源
        最近更新 更多