如何获得Python数组中一个元素的地址
在这篇文章中,我们将讨论如何获得Python数组中某个特定元素的地址。在Python中,我们可以使用numpy创建数组。Numpy代表了用于创建和处理数组的数字Python。我们必须要导入numpy模块
import numpy as np
创建数组的语法。
np.ndarray([element1,element2,….,element n])
方法1:使用数据
我们可以通过数组索引使用数据来获得地址。
语法:
array[index].data
它将返回存在于给定索引的那个元素的内存。下面给出了同样的实现。
例子: Python代码创建一个10个元素的数组,并访问一些元素的内存
# 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)
输出:
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代码获取数组元素的地址细节
# 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’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(5)}
The element present at 5 th index – element 6 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(6)}
The element present at 1 st index – element 2 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(2)}
The element present at 0 th index – element 1 : {‘data’: (94734975551568, False), ‘strides’: None, ‘descr’: [(”, ‘<i8’)], ‘typestr’: ‘<i8’, ‘shape’: (), ‘version’: 3, ‘__ref’: array(1)}