簡體   English   中英

python中2d列表的長度

[英]Length of 2d list in python

我有一個2D列表,例如mylist =[[1,2,3],[4,5,6],[7,8,9]]

有什么方法可以使用len()函數,這樣我可以計算數組索引的長度? 例如:

len(mylist[0:3])
len(mylist[1:3])
len(mylist[0:1])

應該給:

9
6
3

length = sum([len(arr) for arr in mylist])

sum([len(arr) for arr in mylist[0:3]]) = 9
sum([len(arr) for arr in mylist[1:3]]) = 6
sum([len(arr) for arr in mylist[2:3]]) = 3

mylist中每個列表的長度相加以獲得所有元素的長度。
這僅在列表為2D時才能正常工作。 如果mylist某些元素不是列表,誰知道會發生什么...

此外,您可以將其綁定到一個函數:

len2 = lambda l: sum([len(x) for x in l])
len2(mylist[0:3]) = 9
len2(mylist[1:3]) = 6
len2(mylist[2:3]) = 3

您可以展平列表,然后在其上調用len

>>> mylist=[[1,2,3],[4,5,6],[7,8,9]]
>>> import collections
>>> def flatten(l):
...     for el in l:
...         if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
...             for sub in flatten(el):
...                 yield sub
...         else:
...             yield el
...
>>> len(list(flatten(mylist)))
9
>>> len(list(flatten(mylist[1:3])))
6
>>> len(list(flatten(mylist[0:1])))
3

您可以使用reduce來計算像這樣的數組索引的長度,這也可以處理傳遞類似mylist[0:0]

def myLen(myList):
    return reduce(lambda x, y:x+y, [len(x) for x in myList], 0)

myLen(mylist[0:3]) = 9
myLen(mylist[1:3]) = 6
myLen(mylist[0:1]) = 3
myLen(mylist[0:0]) = 0

我喜歡@Haidro的答案,它適用於任意嵌套,但我不喜歡創建中間列表。 這是避免這種情況的變種。

try:
    reduce
except NameError:
    # python3 - reduce is in functools, there is no basestring
    from functools import reduce
    basestring = str

import operator
import collections

def rlen(item):
    """
    rlen - recursive len(), where the "length" of a non-iterable
    is just 1, but the length of anything else is the sum of the
    lengths of its sub-items.
    """
    if isinstance(item, collections.Iterable):
        # A basestring is an Iterable that contains basestrings,
        # i.e., it's endlessly recursive unless we short circuit
        # here.
        if isinstance(item, basestring):
            return len(item)
        return reduce(operator.add, (rlen(x) for x in item), 0)
    return 1

對於它,我還包括一個發電機驅動的,完全遞歸的flatten 請注意,這次對字符串做出更難的決定(上面的短路是非常正確的,因為len(some_string) == sum(len(char) for char in some_string) )。

def flatten(item, keep_strings=False):
    """
    Recursively flatten an iterable into a series of items.  If given
    an already flat item, just returns it.
    """
    if isinstance(item, collections.Iterable):
        # We may want to flatten strings too, but when they're
        # length 1 we have to terminate recursion no matter what.
        if isinstance(item, basestring) and (len(item) == 1 or keep_strings):
            yield item
        else:
            for elem in item:
                for sub in flatten(elem, keep_strings):
                    yield sub
    else:
        yield item

如果你不需要任意嵌套 - 如果你總是確定這只是一個列表列表(或元組列表,列表元組等) - “最佳”方法可能就是簡單的“生成器總和” @Matt Bryant的答案:

len2 = lambda lst: sum(len(x) for x in lst)

len(ast.flatten(lst))怎么樣? 只適用於py2k afaik

它的

from compiler import ast
len(ast.flatten(lst))

以來

ast.flatten([1,2,3]) == [1,2,3]
ast.flatten(mylist[0:2]) == [1,2,3,4,5,6]
ast.flatten(mylist) == [1,2,3,4,5,6,7,8,9]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM