怎么会呢数字连接处理列表

2024-06-26 13:32:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想弄清楚为什么以下代码不起作用:

import numpy as np

failList = [[[1], [2]],
           [[3, 4, 5, 6], [7]],
           [[8], [9]],
           [[10], [11, 12]],
           [[13], [14, 15, 16]]]

goodList = [[[1], [2], [3, 4, 5, 6], [7], [8]],
           [[9], [10], [11, 12], [13], [14, 15, 16]]]

goodList2 = [[[1], [2], [3, 4, 5, 6], [7], [8]],
            [[9], [10], [11, 12], [13], [14, 15, 16]],
            [[9], [10], [11, 12], [13], [14, 15, 16]]]

myLists = [failList, goodList, goodList]

for l in myLists:
    print([len(l[i]) for i in range(len(l))])
    print([len(l[i][j]) for i in range(len(l)) for j in range(len(l[i]))])
    try:
        np.concatenate(l)
        print("worked")
    except:
        print("failed")

输出为:

^{pr2}$

有人能解释一下,为什么第一个列表不能连接,而其他列表可以连接?在


Tags: 代码inimportnumpy列表forlenas
3条回答

原始答案(错误):

根据docs

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).

第一个列表的属性是内部列表的长度不同(分别为6和4)。在你的好列表中,所有内部列表的长度都是相同的5。在

编辑:对不起,我没有注意到其中的一个括号,所以我错误地将您的failList的形状视为错误。在

正确答案是,在故障列表中,子列表的形状不同:

>>> np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).shape
(3,3) # because all lists have the same lengths, so NumPy treats as multi-dim array

>>> np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]).shape
(3,) # because all lists have different lengths, so NumPy treats as an array of lists

连接元组(或列表)中的列表应该具有相同的维度。在

您可以在实现^{cd1>}的github source code中看到第399行。在

if (PyArray_NDIM(arrays[iarrays]) != ndim) {
            PyErr_SetString(PyExc_ValueError,
                            "all the input arrays must have same "
                            "number of dimensions");
            return NULL;
}

PyArray_NDIMdo给出所有维度的长度

在您的例子中,failList中的列表没有相同的维度。 您可以通过下面的代码进行检查。在

^{pr2}$

concatenate从每个列表元素生成一个数组,然后将它们连接到所需的轴上。如果形状不匹配,则会引发错误:

In [80]: failList = [[[1], [2]],
    ...:            [[3, 4, 5, 6], [7]],
    ...:            [[8], [9]],
    ...:            [[10], [11, 12]],
    ...:            [[13], [14, 15, 16]]]
    ...:            
In [81]: [np.array(a) for a in failList]
Out[81]: 
[array([[1],
        [2]]),
 array([list([3, 4, 5, 6]), list([7])], dtype=object),
 array([[8],
        [9]]),
 array([list([10]), list([11, 12])], dtype=object),
 array([list([13]), list([14, 15, 16])], dtype=object)]
In [82]: [np.array(a).shape for a in failList]
Out[82]: [(2, 1), (2,), (2, 1), (2,), (2,)]
In [83]: np.concatenate([np.array(a) for a in failList])
                                     -
ValueError                                Traceback (most recent call last)
<ipython-input-83-c3434632bd7e> in <module>()
  > 1 np.concatenate([np.array(a) for a in failList])

ValueError: all the input arrays must have same number of dimensions

failedList的元素对于不同类型的数组,有些是二维数值的,有些是一维对象。concatenate无法加入这些。在

column_stack有效:

^{pr2}$

这是因为它将(2,)形状的数组整形为(2,1)。现在它有一个5(2,1)数组的列表,它可以在第二维度上连接这些数组,从而生成一个(2,5)数组。但请注意,它是object dtype。有些元素是整数,有些是列表(大小不同)。在

相关问题 更多 >