# Python中的数组用法指南|S2（重要函数）

2021年4月2日11:43:12 发表评论 668 次浏览

Python中的数组|S1(简介和函数)

1.typecode：-此功能返回数据类型通过哪个数组初始化。

2.itemsize：-此函数返回尺寸以字节为单位单数组元素。

3. buffer_info()：-返回表示存储数组的地址和元素数在里面。

``````# Python code to demonstrate the working of
# typecode, itemsize, buffer_info()

# importing "array" for array operations
import array

# initializing array with array values
# initializes array with signed integers
arr = array.array( 'i' , [ 1 , 2 , 3 , 1 , 2 , 5 ])

# using typecode to print datatype of array
print ( "The datatype of array is : " )
print (arr.typecode)

# using itemsize to print itemsize of array
print ( "The itemsize of array is : " )
print (arr.itemsize)

# using buffer_info() to print buffer info. of array
print ( "The buffer info. of array is : " )
print (arr.buffer_info())``````

``````The datatype of array is :
i
The itemsize of array is :
4
The buffer info. of array is :
(29784224, 6)``````

``````# importing "array" using * for array operations
from array import *

# initializing array with array values
# initializes array with signed integers
arr = array( 'i' , [ 1 , 2 , 3 , 1 , 2 , 5 ])

print (arr)``````

``array('i', [1, 2, 3, 1, 2, 5])``

4. count()：-此功能计算出现次数数组中提到的参数。

5.延伸：-此功能追加整个数组在其对指定数组的参数中提到的内容。

``````# Python code to demonstrate the working of
# count() and extend()

# importing "array" for array operations
import array

# initializing array 1 with array values
# initializes array with signed integers
arr1 = array.array( 'i' , [ 1 , 2 , 3 , 1 , 2 , 5 ])

# initializing array 2 with array values
# initializes array with signed integers
arr2 = array.array( 'i' , [ 1 , 2 , 3 ])

# using count() to count occurrences of 1 in array
print ( "The occurrences of 1 in array is : " )
print (arr1.count( 1 ))

# using extend() to add array 2 elements to array 1
arr1.extend(arr2)

print ( "The modified array is : " )
for i in range ( 0 , 9 ):
print (arr1[i])``````

``````The occurrences of 1 in array is :
2
The modified array is :
1
2
3
1
2
5
1
2
3``````

6. fromlist(清单)：-此功能用于追加清单在论点中提到到数组末尾.

7. tolist()：-此功能用于将数组转换为列表.

``````# Python code to demonstrate the working of
# fromlist() and tolist()

# importing "array" for array operations
import array

# initializing array with array values
# initializes array with signed integers
arr = array.array( 'i' , [ 1 , 2 , 3 , 1 , 2 , 5 ])

# initializing list
li = [ 1 , 2 , 3 ]

# using fromlist() to append list at end of array
arr.fromlist(li)

# printing the modified array
print ( "The modified array is : " , end = "")
for i in range ( 0 , 9 ):
print (arr[i], end = " " )

# using tolist() to convert array into list
li2 = arr.tolist()

print ( "\r" )

# printing the new list
print ( "The new list created is : " , end = "")
for i in range ( 0 , len (li2)):
print (li2[i], end = " " )``````

``````The modified array is : 1 2 3 1 2 5 1 2 3
The new list created is : 1 2 3 1 2 5 1 2 3``````