python添加數組元素
An array can be declared by using "array" module in Python.
可以通過在Python中使用“數組”模塊來聲明數組 。
Syntax to import "array" module:
導入“數組”模塊的語法:
import array as array_alias_name
Here, import is the command to import Module, "array" is the name of the module and "array_alias_name" is an alias to "array" that can be used in the program instead of module name "array".
在這里, import是導入Module的命令, “ array”是模塊的名稱, “ array_alias_name”是“ array”的別名,可以在程序中使用它而不是模塊名稱“ array” 。
Array declaration:
數組聲明:
To declare an "array" in Python, we can follow following syntax:
要在Python中聲明“數組” ,我們可以遵循以下語法:
array_name = array_alias_name.array(type_code, elements)
Here,
這里,
array_name is the name of the array.
array_name是數組的名稱。
array_alias_name is the name of an alias - which we define importing the "array module".
array_alias_name是別名的名稱-我們定義了導入“ array module”的名稱 。
type_code is the single character value – which defines the type of the array elements is the list of the elements of given type_code.
type_code是單個字符值–定義數組元素的類型是給定type_code的元素列表。
添加元素 (Adding elements)
We can add elements to an array by using Array.insert() and Array.append() methods in Python.
我們可以使用Python中的Array.insert()和Array.append()方法將元素添加到數組中。
Example:
例:
# Adding Elements to an Array in Python
# importing "array" modules
import array as arr
# int array
arr1 = arr.array('i', [10, 20, 30])
print ("Array arr1 : ", end =" ")
for i in range (0, 3):
print (arr1[i], end =" ")
print()
# inserting elements using insert()
arr1.insert(1, 40)
print ("Array arr1 : ", end =" ")
for i in (arr1):
print (i, end =" ")
print()
# float array
arr2 = arr.array('d', [22.5, 33.2, 43.3])
print ("Array arr2 : ", end =" ")
for i in range (0, 3):
print (arr2[i], end =" ")
print()
# inserting elements using append()
arr2.append(54.4)
print ("Array arr2 : ", end =" ")
for i in (arr2):
print (i, end =" ")
print()
Output
輸出量
Array arr1 : 10 20 30
Array arr1 : 10 40 20 30
Array arr2 : 22.5 33.2 43.3
Array arr2 : 22.5 33.2 43.3 54.4
翻譯自: https://www.includehelp.com/python/adding-elements-to-an-array.aspx
python添加數組元素