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

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

问题描述

我有一个像这样的列表:

I have a list of lists like this:

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

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

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)

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

Is there a simpler way to do it in Python ?

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

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)

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

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

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

推荐答案

在这种情况下如何使用 numpy 数组,因为 L[i][j].size 随 i 和 j 变化.在这种情况下可以使用数组吗?

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.

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)

在这个例子中,L 是 python list 对象的 numpy.ndarray.

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

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

锯齿状数组的算术运算

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

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)

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

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