append the same element to several sublists in python

折月煮酒 提交于 2019-12-12 17:56:15

问题


I have a list of lists like this:

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

I want to append the integer 11 to the subsublists 1 and 3. I can do something like:

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

Is there a simpler way to do it in Python ?

Because in my case, let's say I have a list with 100 sublists, and these sublists have 100 sublists (comparable to a (100,100)-matrix) and I want to append a value to the sublists from nb 50 to 75 of the sublists from nb 10 to 20.

So right now I do something like:

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

Is there a more efficient way ? Like with numpy arrays we can do

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

回答1:


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 ?

Yes, but the dtype is object in such case.

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)

In this example, L is a numpy.ndarray of python list objects.

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

Arithmetic operation on jagged array

It is possible to perform efficient arithmetic operation on the jagged array like L using 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)


来源:https://stackoverflow.com/questions/36981925/append-the-same-element-to-several-sublists-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!