列表内容的长度,里面有列表

length of list contents with lists inside

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

示例:

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

输出

4

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

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

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

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

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

由于函数式方法在现代 Python 中有时不受欢迎,您也可以使用 list comprehension (actually a generator comprehension):

print(sum(len(x) for x in Names))
# 6
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)

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

中则增加 1