//操作 Python 列表
procedure TForm1.WorkWithPythonList;
var
PyList, PyItem: PPyObject;
I: Integer;
begin
PythonEngine1.LoadDll;
// 【第1段】创建 Python 列表
PyList := PythonEngine1.PyList_New(0); // 空列表
// 【第2段】向列表添加元素
for I := 1 to 5 do
begin
PyItem := PythonEngine1.PyLong_FromLong(I * 10);
PythonEngine1.PyList_Append(PyList, PyItem);
PythonEngine1.Py_DecRef(PyItem); // 列表已引用,可以释放临时引用
end;
// 【第3段】将列表注入 Python
PythonEngine1.PyDict_SetItemString(
PythonEngine1.GetMainModule.__dict__,
'my_list',
PyList
);
PythonEngine1.Py_DecRef(PyList);
// 【第4段】Python 中使用列表
PythonEngine1.ExecString(
'print(f"列表: {my_list}")' + sLineBreak +
'print(f"总和: {sum(my_list)}")'
);
end;