1. 使用全局变量:
```python
def process_array(arr):
global my_array
my_array = arr
调用函数,传入数组
process_array([1, 2, 3, 4, 5])
在函数外部使用全局变量
print(my_array) 输出:[1, 2, 3, 4, 5]
2. 直接在函数内部操作传入的列表:
```python
def process_array(arr):
在这里编写你的数组处理逻辑
arr.append(6) 向列表末尾添加一个元素
return arr
调用函数,传入列表
new_list = process_array([1, 2, 3, 4, 5])
输出处理后的列表
print(new_list) 输出:[1, 2, 3, 4, 5, 6]
3. 使用`ctypes`库调用C++中的数组:
```python
import ctypes
定义C++函数
假设这是C++代码:
void process_array(float* arr, int size) {
for (int i = 0; i < size; ++i) {
arr[i] *= 2;
}
}
创建C++函数
lib = ctypes.CDLL('./my_lib.so') 假设库文件名为my_lib.so
lib.process_array.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int]
lib.process_array.restype = None
创建Python中的float数组
arr = (ctypes.c_float * 5)()
arr = 1.0
arr = 2.0
arr = 3.0
arr = 4.0
arr = 5.0
调用C++函数
lib.process_array(arr, 5)
输出处理后的Python数组
print([arr[i] for i in range(5)]) 输出:[2.0, 4.0, 6.0, 8.0, 10.0]
以上是Python中函数调用数组的一些方法。请根据你的具体需求选择合适的方法