【问题标题】:How to determine the dimensions of a mix of lists and arrays?如何确定列表和数组混合的维度?
【发布时间】:2016-08-31 17:21:57
【问题描述】:

考虑一个由数组组成的对象:

a=[array([1,2,3]),array(2,5,10,20)]

有趣的是,这东西有两个维度。列表本身是一维的,它包含一维的对象。有没有一种简单的方法来区分上面的a 和像b=[1,3,6,9,11] 这样的列表,它只是一维的,c=1,它是一个 0D 标量?我想要一个函数dimens(),这样dimens(a) 返回2dimens(b) 返回1,而dimens(c) 返回0

我通过测试列表中第一个元素的形状来做到这一点,但我觉得可能有一种更简洁的方法。

【问题讨论】:

    标签: python arrays python-2.7 list numpy


    【解决方案1】:
    def dimens(l):
        try:
            size = len(l)
        except TypeError: # not an iterable
            return 0
        else:
            if size: # non-empty iterable
                return 1 + max(map(dimens, l))
            else: # empty iterable
                return 1
    
    print(dimens([[1,2,3],[2,5,10,[1,2]]]))
    print(dimens(np.zeros([6,5,4,3,2,1])))
    

    输出

    3
    6
    

    【讨论】:

    • 不错。什么设置了它将检测到的最大尺寸的限制?它上升到 4,这很酷,但我用 zeros([6,5,4,3,2,1]) 对其进行了测试,它应该是 6 维的,它只说 4。无论如何,最高 4 对我正在做的事情来说很好。谢谢。
    • 该代码现在也适用于 numpy 数组,并为 zeros([6,5,4,3,2,1]) 返回 6
    【解决方案2】:

    这是我的功能:

    def dimens(x):
        s=shape(x)
        if len(s)==0:
            return 0 #the input was a scalar
        s2=shape(x[0])
        if len(s2)==0:
            return 1 #each element of the list was a scalar
        else:
            #each element of the list was a vector or array
            if len(s2)==1:
                if len(shape(s2[0]))==0:
                    return 2 #the first element of the top list was a 1D vector and the first element of that vector was a scalar
            return 3 #there were more than 2 dimensions involved
    

    测试:

    a=[array([1,2,3]),array([2,5,10,20])]
    b=[1,3,6,9,11]
    c=1
    d=[[a]]+[[a]]
    
    print dimens(a)
    2
    print dimens(b)
    1
    print dimens(c)
    0
    print dimens(d)
    3
    

    限制:

    • 最多只能达到三个维度(这对我的应用程序来说已经足够了)
    • 仅测试第一个元素,因此它假定每个元素具有相同的维度(这对我的应用程序来说很好,因为我的 2D 案例将是所有数组的列表,而不是包含数组和标量混合的列表)

    谁能做得更好?

    【讨论】:

      【解决方案3】:

      可以使用isinstance方法来区分两个数组

      让我们考虑第一个列表

      a = [1,2,3]
      

      这里的第一个元素是一个整数,因此isinstance(a[0],int) 将返回 true

      对于第二个数组b = [[1,2][3,4]],第一个元素是一个数组,所以isinstance(b[0],int) 将返回false。 您可以使用isinstance(b[0],list)查看第二个列表

      我使用列表代替数组,但它也适用于数组

      【讨论】:

        猜你喜欢
        • 2018-02-03
        • 2012-07-04
        • 1970-01-01
        • 2013-05-22
        • 1970-01-01
        • 2021-04-15
        • 2015-07-29
        • 2013-05-30
        • 1970-01-01
        相关资源
        最近更新 更多