相同的元素追加到蟒蛇几个子列表 [英] append the same element to several sublists in python

查看:124
本文介绍了相同的元素追加到蟒蛇几个子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我要整11追加到subsublists 1和3。我可以这样做:

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

有没有更简单的方法来做到这一点在Python?

由于在我的情况,让我们说我有100子列表清单,而这些子列表有100子列表(相当于一个(100,100) - 矩阵),我想对某个值从NB 50的子列表追加到75从NB 10子列表为20。

所以现在我做这样的事情:

 为我的range(10,21):
    对于j的范围(50,76):
        L [i] [j]的.append(值)

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

  L = [10..21,50..76] =价值


解决方案

  

由于l如何在这种情况下使用numpy的数组[我] [J] .size与i和j的变化。是否有可能在这种情况下使用数组?


是的,但 DTYPE 对象在这种情况下。

  L = [[[1,2,3],[4,5]],[[6,7,8,9],[10]]]
L = np.array(L)#L为列表的ndarray
#阵列([[[1,2,3],[4,5]],[[6,7,8,9],[10]]],DTYPE =对象)
值= 100
因为我在L [0:1,0:2] .flatten():
  i.append(值)
#阵列([[[1,2,3,100],[4,5,100]],[[6,7,8,9],[10]]],DTYPE =对象)

在这个例子中, numpy.ndarray 列表的对象。

 键入(L)
#<键入'numpy.ndarray'>
类型(L [0,0])
#<类型列表'>

锯齿形阵列上

算术运算

有可能像 L时锯齿形阵列上执行高效的运算使用numpy的。

 马尔= np.vectorize(np.array,otypes = [np.ndarray])
L = [[[1,2,3],[4,5]],[[6,7,8,9],[10]]]
L =马尔(L)#,L是ndarray的ndarray
L +大号
#阵列([[阵列([2,4,6]),阵列([8,10])],[阵列([12,14,16,18]),阵列([20])]] DTYPE =对象)

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

解决方案

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)

这篇关于相同的元素追加到蟒蛇几个子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆