如何获取Python数组中元素的地址?
在本文中,我们将讨论获取Python数组中特定元素的地址。在Python,我们可以使用 numpy 创建数组。 Numpy 代表用于创建和处理数组的数字Python 。我们必须导入 numpy 模块
import numpy as np
创建数组的语法:
np.ndarray([element1,element2,….,element n])
方法一:使用数据
我们可以通过数组索引使用数据来获取地址。
句法:
array[index].data
它将返回存在于给定索引处的该元素的内存。下面给出了相同的实现。
示例: Python代码创建一个包含 10 个元素的数组并访问某些元素的内存
Python3
# import numpy module
import numpy as np
# create an array of 10 elements
a = np.array([1, 2, 3, 4, 5, 6, 7, 34, 56, 78])
# get index 4 element address
print("The element present at 4 th index - element",
a[4], ":", a[4].data)
# get index 5 element address
print("The element present at 5 th index - element",
a[5], ":", a[5].data)
# get index 1 element address
print("The element present at 1 st index - element",
a[1], ":", a[1].data)
# get index 0 element address
print("The element present at 0 th index - element",
a[0], ":", a[0].data)
Python3
# import numpy module
import numpy as np
# create an array of 10 elements
a = np.array([1, 2, 3, 4, 5, 6, 7, 34, 56, 78])
# get index 4 element address
print("The element present at 4 th index - element",
a[4], ":", a[4].__array_interface__)
# get index 5 element address
print("The element present at 5 th index - element",
a[5], ":", a[5].__array_interface__)
# get index 1 element address
print("The element present at 1 st index - element",
a[1], ":", a[1].__array_interface__)
# get index 0 element address
print("The element present at 0 th index - element",
a[0], ":", a[0].__array_interface__)
输出:
The element present at 4 th index – element 5 :
The element present at 5 th index – element 6 :
The element present at 1 st index – element 2 :
The element present at 0 th index – element 1 :
方法 2:使用 __array_interface__
我们可以通过使用此方法获取所有内存详细信息,因此显然也会返回内存地址。
句法:
arr[index].__array_interface__
示例:获取数组元素地址详细信息的Python代码
蟒蛇3
# import numpy module
import numpy as np
# create an array of 10 elements
a = np.array([1, 2, 3, 4, 5, 6, 7, 34, 56, 78])
# get index 4 element address
print("The element present at 4 th index - element",
a[4], ":", a[4].__array_interface__)
# get index 5 element address
print("The element present at 5 th index - element",
a[5], ":", a[5].__array_interface__)
# get index 1 element address
print("The element present at 1 st index - element",
a[1], ":", a[1].__array_interface__)
# get index 0 element address
print("The element present at 0 th index - element",
a[0], ":", a[0].__array_interface__)
输出:
The element present at 4 th index – element 5 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘ The element present at 5 th index – element 6 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘ The element present at 1 st index – element 2 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘ The element present at 0 th index – element 1 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘