2022年 11月 8日

python添加数组元素_在Python中向数组添加元素

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:

例:

  1. # Adding Elements to an Array in Python
  2. # importing "array" modules
  3. import array as arr
  4. # int array
  5. arr1 = arr.array('i', [10, 20, 30])
  6. print ("Array arr1 : ", end =" ")
  7. for i in range (0, 3):
  8. print (arr1[i], end =" ")
  9. print()
  10. # inserting elements using insert()
  11. arr1.insert(1, 40)
  12. print ("Array arr1 : ", end =" ")
  13. for i in (arr1):
  14. print (i, end =" ")
  15. print()
  16. # float array
  17. arr2 = arr.array('d', [22.5, 33.2, 43.3])
  18. print ("Array arr2 : ", end =" ")
  19. for i in range (0, 3):
  20. print (arr2[i], end =" ")
  21. print()
  22. # inserting elements using append()
  23. arr2.append(54.4)
  24. print ("Array arr2 : ", end =" ")
  25. for i in (arr2):
  26. print (i, end =" ")
  27. print()

Output

输出量

  1. Array arr1 : 10 20 30
  2. Array arr1 : 10 40 20 30
  3. Array arr2 : 22.5 33.2 43.3
  4. Array arr2 : 22.5 33.2 43.3 54.4




翻译自: https://www.includehelp.com/python/adding-elements-to-an-array.aspx

python添加数组元素