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:

例:

# 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添加数组元素

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值