Python 如何找到多维列表的长度?
如何计算多维列表的长度Python 如何找到多维列表的长度?,python,python-2.7,Python,Python 2.7,如何计算多维列表的长度 multilist = [['1', '2', 'Ham', '4'], ['5', 'ABCD', 'Foo'], ['Bar', 'Lu', 'Shou']] counter = 0 for minilist in multilist: for value in minilist: counter += 1 print(counter) 我自己想出了一个方法,但这是在多维列表中查找值数量的唯一方法吗 multilist = [['1', '
multilist = [['1', '2', 'Ham', '4'], ['5', 'ABCD', 'Foo'], ['Bar', 'Lu', 'Shou']]
counter = 0
for minilist in multilist:
for value in minilist:
counter += 1
print(counter)
我自己想出了一个方法,但这是在多维列表中查找值数量的唯一方法吗
multilist = [['1', '2', 'Ham', '4'], ['5', 'ABCD', 'Foo'], ['Bar', 'Lu', 'Shou']]
counter = 0
for minilist in multilist:
for value in minilist:
counter += 1
print(counter)
我很确定有一种更简单的方法来计算多维列表的长度,但是len(list)不起作用,因为它只给出了内部列表的数量。还有比这更有效的方法吗?怎么样:
sum(len(x) for x in multilist)
@mgilson解决方案的替代方案
sum(map(len, multilist))
另一种选择(就是这个或是看数学课)
这允许不同程度的“多维性”(如果这是一个词的话)共存
例如:
或者,允许不同的集合类型
def getLength(element):
try:
element.__iter__
return sum([getLength(i) for i in element])
except:
return 1
例如:
(注意,尽管字符串是可iterable的,但它们没有_iter__)方法包装,因此不会引起任何问题…如果您想要任何n维列表中的项数,则需要使用如下递归函数:
def List_Amount(List):
return _List_Amount(List)
def _List_Amount(List):
counter = 0
if isinstance(List, list):
for l in List:
c = _List_Amount(l)
counter+=c
return counter
else:
return 1
这将返回列表中的项目数,无论列表的形状或大小,Python总是存在的。列表是否限制为两个级别,或者可以更深一些?如果数据结构中有字符串,则此代码的最后版本将中断,因为
“a”
是可编辑的,它的唯一成员也是“A”
(在达到递归限制时导致错误)。我想,如果创建一个包含自身引用的列表,它也会无限递归,但这不太可能是偶然发生的。此外,您将无法正确计算作为字典值的容器中的项(尽管您将计算元组键中的值)。我的python版本(2.7.2)为“字符串”引发了一个错误<代码>str.\uuuuiter\uuuuu确实存在于Python 3中,甚至在Python 2中,调用iter(“foo”)
也可以正常工作。
>>> getLength([ 1, 2, (1,3,4), {4:3} ])
6
>>> getLength(["cat","dog"])
2
def List_Amount(List):
return _List_Amount(List)
def _List_Amount(List):
counter = 0
if isinstance(List, list):
for l in List:
c = _List_Amount(l)
counter+=c
return counter
else:
return 1