介紹
在 Python 中,列表是一種線性數據結構,可以存儲異構元素。它不需要定義,可以根據需要收縮和擴展。另一方面,NumPy 數組是一種可以存儲同質元素的數據結構。它是使用 NumPy 庫在 Python 中實現的。這個庫在處理多維數組時非常有效。它在處理大量數據元素時也非常高效。NumPy 數組使用的內存比 List 數據結構少。NumPy 數組和列表都可以通過它們的索引值來標識。
NumPy 庫提供了兩種在 Python 中將列錶轉換為數組的方法。
- 使用 numpy.array()
- 使用 numpy.asarray()
方法 1:使用 numpy.array()
在 Python 中,將列錶轉換為 NumPy 數組的最簡單方法是使用 numpy.array()函數。它接受一個參數並返回一個 NumPy 數組。它在內存中創建新的副本。
程序 1
# importing library of the array in python
import numpy
# initilizing elements of the list
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# converting elements of the list into array elements
arr = numpy.array(a)
# displaying elements of the list
print ("List: ", a)
# displaying elements of the array
print ("Array: ", arr)
輸出:
List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Array: [1 2 3 4 5 6 7 8 9]
方法 2:使用 numpy.asarray()
在 Python 中,第二個方法是將列錶轉換為 numpy 數組的 numpy.asarray()函數。它接受一個參數並將其轉換為 NumPy 數組。它不會在內存中創建新副本。在這種情況下,對原始數組所做的所有更改都會反映在 NumPy 數組上。
程序 2
# importing library of the array in python
import numpy
# initilizing elements of the list
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# converting elements of the list into array elements
arr = numpy.asarray(a)
# displaying elements of the list
print ("List:", a)
# displaying elements of the array
print ("Array: ", arr)
輸出:
List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Array: [1 2 3 4 5 6 7 8 9]
程序 3
# importing library of the NumPy array in python
import numpy
# initilizing elements of the list
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# converting elements of the list into array elements
arr = numpy.asarray(lst)
# displaying elements of the list
print ("List:", lst)
# displaying elements of the array
print ("arr: ", arr)
# made another array out of arr using asarray function
arr1 = numpy.asarray(arr)
#displaying elements of the arr1 before the changes made
print("arr1: " , arr1)
#change made in arr1
arr1[3] = 23
#displaying arr1 , arr , list after the change has been made
print("lst: " , lst)
print("arr: " , arr)
print("arr1: " , arr1)
輸出:
List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr: [1 2 3 4 5 6 7 8 9]
arr1: [1 2 3 4 5 6 7 8 9]
lst: [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr: [ 1 2 3 23 5 6 7 8 9]
arr1: [ 1 2 3 23 5 6 7 8 9]
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/297262.html