python数组添加数组
Pythondoesn’thaveanyspecificdatatypeasanarray.WecanuseListthathasallthecharacteristicsofanarray.
Python没有任何特定的数据类型作为数组。我们可以使用具有数组所有特征的List。
Pythonarraymodulecanbeusedtocreateanarrayofintegersandfloating-pointnumbers.
Python数组模块可用于创建整数和浮点数的数组。
Ifyouwanttodosomemathematicaloperationsonanarray,youshouldusetheNumPymodule.
如果要对数组进行一些数学运算,则应使用NumPy模块。
Python添加到数组(1.PythonaddtoArray)
IfyouareusingListasanarray,youcanuseitsappend(),insert(),andextend()functions.YoucanreadmoreaboutitatPythonaddtoList.如果将List用作数组,则可以使用其append(),insert()和extend()函数。您可以在PythonaddtoList中阅读有关它的更多信息。Ifyouareusingarraymodule,youcanusetheconcatenationusingthe+operator,append(),insert(),andextend()functionstoaddelementstothearray.如果使用的是数组模块,则可以使用+运算符,append(),insert()和extend()函数进行串联,以将元素添加到数组中。IfyouareusingNumPyarrays,usetheappend()andinsert()function.如果您使用的是NumPy数组,请使用append()和insert()函数。
2.使用数组模块将元素添加到数组(2.AddingelementstoanArrayusingarraymodule)
Using+operator:anewarrayisreturnedwiththeelementsfromboththearrays.使用+运算符:返回一个新数组,其中包含两个数组中的元素。append():addstheelementtotheendofthearray.append():将元素添加到数组的末尾。insert():insertstheelementbeforethegivenindexofthearray.insert():将元素插入到数组的给定索引之前。extend():usedtoappendthegivenarrayelementstothisarray.extend():用于将给定的数组元素附加到此数组。
importarray
arr1=array.array('i',[1,2,3])
arr2=array.array('i',[4,5,6])
print(arr1)#array('i',[1,2,3])
print(arr2)#array('i',[4,5,6])
arr3=arr1+arr2
print(arr3)#array('i',[1,2,3,4,5,6])
arr1.append(4)
print(arr1)#array('i',[1,2,3,4])
arr1.insert(0,10)
print(arr1)#array('i',[10,1,2,3,4])
arr1.extend(arr2)
print(arr1)#array('i',[10,1,2,3,4,4,5,6])
3.向NumPy数组添加元素(3.AddingelementstotheNumPyArray)
append():thegivenvaluesareaddedtotheendofthearray.Iftheaxisisnotprovided,thenthearraysareflattenedbeforeappending.append():将给定值添加到数组的末尾。如果未提供轴,则在附加之前将阵列弄平。insert():usedtoinsertvaluesatthegivenindex.Wecaninsertelementsbasedontheaxis,otherwise,theelementswillbeflattenedbeforetheinsertoperation.insert():用于在给定索引处插入值。我们可以基于轴插入元素,否则,将在插入操作之前将元素展平。
>>>importnumpyasnp
>>>np_arr1=np.array([[1,2],[3,4]])
>>>np_arr2=np.array([[10,20],[30,40]])
>>>
>>>np.append(np_arr1,np_arr2)
array([1,2,3,4,10,20,30,40])
>>>
>>>np.append(np_arr1,np_arr2,axis=0)
array([[1,2],
[3,4],
[10,20],
[30,40]])
>>>
>>>np.append(np_arr1,np_arr2,axis=1)
array([[1,2,10,20],
[3,4,30,40]])
>>>
>>>np.insert(np_arr1,1,np_arr2,axis=0)
array([[1,2],
[10,20],
[30,40],
[3,4]])
>>>
>>>np.insert(np_arr1,1,np_arr2,axis=1)
array([[1,10,30,2],
[3,20,40,4]])
>>>
4.参考(4.References)
arraymodule阵列模组numpy.append()docsnumpy.append()文档
翻译自:https://www.journaldev.com/33185/python-add-to-array
python数组添加数组