是否存在用于获取列表中包含列表的列表项总数的命令?
示例:
Names = [['Mark'], ['John', 'Mary'], ['Cindy', 'Tom'], ['Ben']]
print (len(Names))
输出
4
但是我希望列表项的总数为6,所以结果是6。我刚开始学习python,所以对我要轻松一些。
答案 0 :(得分:2)
您可以使用map
将函数应用于可迭代对象的每个元素。在这里,我们应用len
函数和sum
结果:
Names = [['Mark'], ['John', 'Mary'], ['Cindy', 'Tom'], ['Ben']]
print(sum(map(len, Names)))
# 6
仅当Names
的每个元素实际上是一个list
时,此(以及所有其他答案)才有效。如果其中之一是str
,它将添加字符串的长度,如果没有长度(如int
或float
),它将引发{{1} }。
由于在现代Python中有时无法使用功能性方法,因此您也可以使用list comprehension(实际上是generator comprehension):
TypeError
答案 1 :(得分:0)
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)
答案 2 :(得分:0)
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 :(得分:0)
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。