Skip to main content
 首页 » 编程设计

python之将相同的元素 append 到python中的多个子列表

2024年10月24日24lyj

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

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

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

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

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

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

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

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 ?

是的,但是在这种情况下 dtype 是 object。

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) 

在此示例中,L 是 python list 对象的 numpy.ndarray。

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

交错数组的算术运算

可以使用 numpy 对像 L 这样的锯齿状数组执行高效的算术运算。

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)