代码之家  ›  专栏  ›  技术社区  ›  jss367

在python中查找列表的大小/内部结构

  •  4
  • jss367  · 技术社区  · 7 年前

    如果我有单子 c 像这样:

    a = [1,2,3,4]
    c = [a,a]
    

    找到长度为2的列表的最简单方法是什么,其中每个元素都是长度为4的列表?如果我这样做 len(c) 我得到 2 但它并没有给出这些元素是列表或其大小的任何指示,除非我显式地执行如下操作

    print(type(c[0]))
    print(len(c[0]))
    print(len(c[1]))
    

    我可以做点什么

    import numpy as np
    np.asarray(c).shape
    

    这给了我 (2,4) ,但这仅在内部列表大小相等时有效。如果相反,列表如下

    a = [1,2,3,4]
    b = [1,2]
    d = [a,b]
    

    然后 np.asarray(d).shape 就给我 (2,) . 在这种情况下,我可以做

    import pandas as pd
    df = pd.DataFrame(d)
    df.info()
    
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 2 entries, 0 to 1
    Data columns (total 4 columns):
    0    2 non-null int64
    1    2 non-null int64
    2    1 non-null float64
    3    1 non-null float64
    dtypes: float64(2), int64(2)
    memory usage: 144.0 bytes
    

    从这一点上,我可以看出,原始列表中有列表,但我希望能够在不使用熊猫的情况下看到这一点。查看列表内部结构的最佳方法是什么?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Olivier Melançon iacob    7 年前

    根据预期的输出格式,可以编写递归函数,返回长度和形状的嵌套元组。

    代码

    def shape(lst):
        length = len(lst)
        shp = tuple(shape(sub) if isinstance(sub, list) else 0 for sub in lst)
        if any(x != 0 for x in shp):
            return length, shp
        else:
            return length
    

    实例

    lst = [[1, 2, 3, 4], [1, 2, 3, 4]]
    print(shape(lst)) # (2, (4, 4))
    
    lst = [1, [1, 2]]
    print(shape(lst)) # (2, (0, 2))
    
    lst = [1, [1, [1]]]
    print(shape(lst)) # (2, (0, (2, (0, 1))))
    
        2
  •  1
  •   Mauro Baraldi    7 年前

    这种方法返回list元素的类型,第一项是父列表信息。

    def check(item):
        res = [(type(item), len(item))]
        for i in item:
            res.append((type(i), (len(i) if hasattr(i, '__len__') else None)))
        return res
    
    >>> a = [1,2,3,4]
    >>> c = [a,a]
    >>> check(c)
    [(list, 2), (list, 4), (list, 4)]