Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中正确地向数组添加元素_Python_Python 3.x - Fatal编程技术网

如何在Python中正确地向数组添加元素

如何在Python中正确地向数组添加元素,python,python-3.x,Python,Python 3.x,我有两个数组,如下代码所示(A和B)。我想把C=[[1,2,3,11],[4,5,6,12],[7,8,9,13]作为输出 我正在努力,但我唯一能做到的是: A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [11, 12, 13] C = [[x, y] for x, y in zip(A, B)] print(C) # Output: [[[1, 2, 3], 11], [[4, 5, 6], 12], [[7, 8, 9], 13]] 您只需要创建一个

我有两个数组,如下代码所示(A和B)。我想把C=[[1,2,3,11],[4,5,6,12],[7,8,9,13]作为输出

我正在努力,但我唯一能做到的是:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [11, 12, 13]
C = [[x, y] for x, y in zip(A, B)]

print(C)
# Output: [[[1, 2, 3], 11], [[4, 5, 6], 12], [[7, 8, 9], 13]]

您只需要创建一个单个元素(
y
)的数组,然后将这两个列表添加到一起

 [x + [y] for x, y in zip(A, B)]
可以用numpy

import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = np.array([[11, 12, 13]]).T
C = np.append(A,B,axis=1)

可能您必须根据所需的形状将C转置。

如果不需要新列表,修改
a
就足够了:

for a, b in zip(A, B):
    a.append(b)

它更有效,至少对于较长的内部列表是如此。

在A和B中嵌套的级别都不相同,这就是为什么会得到一个奇怪的答案。A是一个列表,而B只是一个列表

解决 如果要在原地添加:

A.append(B)
# Output: A = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
否则:

C = A + [B]
使A和B保持不变,并创建一个新的联接列表

时间安排 结论:对于这个问题,你用哪种方式做并不重要,因为每个病例的时间安排都差不多。不过,有些方法更具可读性

计时代码:

import timeit

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [10, 11, 12]


def append_arrs(arrs=(A, B)):
    a, b = arrs
    a.append(b)
    return a


def plus_arrs(arrs=(A, B)):
    return arrs[0] + [arrs[1]]


def loopadd_arrs(arrs=(A, B)):
    return [x + [y] for x, y in zip(*arrs)]


def listadd_arrs(arrs=(A, B)):
    a, b = arrs
    return list((*a, b))


func_list = ["append_arrs", "plus_arrs", "loopadd_arrs", "listadd_arrs"]


for func in func_list:
    t = timeit.timeit(stmt=f'{func}', setup=f'from __main__ import {func}')
    print(f"Time for {func}: {t}")

如果您在浏览器中搜索“将元素添加到Python列表”,您会找到比我们在这里所能处理的更好的解释这一点的参考资料。@Prune好吧,因为我进行了搜索,所以我来这里问这个问题。它是否需要是一个新列表,或者修改
A
也可以吗?我有两个数组,如下代码所示,它们是列表,而不是数组。请更具体地说明问题所在。