将相同的元素附加到 python 中的多个子列表

append the same element to several sublists in python

我有一个这样的列表列表:

L=[[[1,2,3],[4,5]],[[6,7,8,9],[10]]]

我想将整数 11 附加到子列表 1 和 3。我可以这样做:

L[0][2].append(11)
L[1][2].append(11)

在 Python 中有更简单的方法吗?

因为在我的例子中,假设我有一个包含 100 个子列表的列表,这些子列表有 100 个子列表(相当于 (100,100)-矩阵),我想将一个值附加到从 nb 50 到从 nb 10 到 20 的 75 个子列表。

所以现在我会做类似的事情:

for i in range(10,21):
    for j in range(50,76):
        L[i][j].append(value)

有没有更高效的方法?就像 numpy 数组一样,我们可以做

L=[10..21,50..76]=value

how to use numpy arrays in this case since L[i][j].size changes with i and j. Is it possible to use arrays in this case ?

是的,但在这种情况下 dtypeobject

L=[[[1,2,3],[4,5]],[[6,7,8,9],[10]]]
L=np.array(L) # L is a ndarray of list
# array([[[1, 2, 3], [4, 5]], [[6, 7, 8, 9], [10]]], dtype=object)
value=100
for i in L[0:1,0:2].flatten():
  i.append(value)
# array([[[1, 2, 3, 100], [4, 5, 100]], [[6, 7, 8, 9], [10]]], dtype=object)

在此示例中,Lnumpy.ndarray 个 python list 个对象。

type(L)
# <type 'numpy.ndarray'>
type(L[0,0])
# <type 'list'>

交错数组的算术运算

L这样的交错数组可以使用numpy进行高效的算术运算。

marr = np.vectorize(np.array,otypes=[np.ndarray])
L=[[[1,2,3],[4,5]],[[6,7,8,9],[10]]]
L=marr(L) # L is a ndarray of ndarray
L+L
# array([[array([2, 4, 6]), array([ 8, 10])],[array([12, 14, 16, 18]), array([20])]], dtype=object)