简体   繁体   English

如何查找多维列表的长度?

[英]How to find length of a multi-dimensional list?

How do you find the length of a multi-dimensional list? 你如何找到多维列表的长度?

I've come up with a way myself, but is this the only way to find the number of values in a multi-dimensional list? 我自己想出了一个方法,但这是在多维列表中找到值的唯一方法吗?

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)

I'm pretty sure there is a much simpler way to find the length of a multi-dimensional list, but len(list) does not work, as it only gives the number of lists inside. 我很确定有一种更简单的方法来查找多维列表的长度,但是len(list)不起作用,因为它只给出了列表中的列表数量。 Is there a more efficient method than this? 有比这更有效的方法吗?

怎么样:

sum(len(x) for x in multilist)

替代@ mgilson的解决方案

sum(map(len, multilist))

If you want the number of items in any n-dimensional list then you need to use a recursive function like this: 如果你想要任何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

This will return the number of items in the list no matter the shape or size of your list 无论列表的形状或大小如何,这都将返回列表中的项目数

Another alternative (it's this or watch missed math lectures...) 另一种选择(这是这个或观看错过的数学讲座......)

def getLength(element):
    if isinstance(element, list):
        return sum([getLength(i) for i in element])
    return 1

This allows different degrees of 'multi-dimensionality' (if that were a word) to coexist. 这允许不同程度的“多维度” (如果这是一个单词)共存。

eg: 例如:

>>> getLength([[1,2],3,4])
4

Or, to allow different collection types 或者,允许不同的集合类型

def getLength(element):
    try:
        element.__iter__
        return sum([getLength(i) for i in element])
    except:
        return 1

eg: 例如:

>>> getLength([ 1, 2, (1,3,4), {4:3} ])
6
>>> getLength(["cat","dog"])
2

(Noting that although strings are iterable, they do not have the __iter__ method-wrapper and so will not cause any issues...) (注意尽管字符串是可迭代的,但它们没有__iter__方法包装器,因此不会导致任何问题......)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM