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

标签 python list append nested-lists

我有一个这样的列表:

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 ?

是的,但是在这种情况下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)

在此示例中,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)

关于python - 将相同的元素追加到python中的多个子列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36981925/

相关文章:

python按自定义顺序排序字典列表

ios - append 字典,iOS,Swift

python 设计模式

python - 为什么列表索引必须是整数,而不是元组?

python - pandas 列中 url 的匹配模式

python - 获取 Mechanize 中 br.forms() 的键和值

java - .NET 等同于 Java 的 List.subList()?

Python-从多个列表中查找不匹配的值

Mysql将数据追加到字段中?

string - 如何在 Golang 中使用 Append 方法。语法要求接口(interface)?