在 MATLAB 中使用 Python list 变量
此示例说明如何在 MATLAB® 中使用 Python® list 变量。
要调用接受 list 输入参量的 Python 函数,请创建一个 py.list 变量。要将列表转换为 MATLAB 变量,请调用 cell 函数,然后为列表中的每个元素调用适当的转换函数。
调用接受 list 输入参量的 Python 函数
Python len 函数返回容器中的项目数,其中包括一个 list 对象。
py.help('len')Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
调用 os.listdir 以创建一个名为 P 的由程序组成的 Python list。
P = py.os.listdir("C:\Program Files\MATLAB");
class(P)ans = 'py.list'
显示程序的数量。
py.len(P)
ans =
Python int with properties:
denominator: [1×1 py.int]
imag: [1×1 py.int]
numerator: [1×1 py.int]
real: [1×1 py.int]
2
显示一个元素。
P{2}ans =
Python str with no properties.
R2023a
对 Python 列表进行索引
使用 MATLAB 索引显示列表中的元素。例如,显示 list 中的最后一个元素。MATLAB 返回一个 Python list。
P(end)
ans =
Python list with values:
['R2023a']
Use string, double or cell function to convert to a MATLAB array.
您也可以在 for 循环中循环访问该列表。
for n = P disp(n{1}) end
Python str with no properties.
MATLAB Runtime
Python str with no properties.
R2023a
将 Python list 类型转换为 MATLAB 类型
以下代码使用 MATLAB 变量显示 list P 中的名称。调用 cell 以转换该列表。该列表由 Python 字符串组成,因此调用 char 函数来转换元胞数组的元素。
cP = cell(P);
每个元胞元素名称均为一个 Python 字符串。
class(cP{1})ans = 'py.str'
将 Python 字符串转换为 MATLAB 数据。
mlP = string(cell(P));
显示名称。
for n = 1:numel(cP) disp(mlP{n}) end
MATLAB Runtime R2023a
在 MATLAB 中使用 Python 数值类型列表
Python list 包含任何类型的元素,并且可以包含混合类型的元素。以下代码中使用的 MATLAB double 函数假设 Python list 的所有元素均为数值。
假设您有一个 Python 函数,它返回名为 P 的由整数组成的 list。要运行此代码,请用以下值创建该变量。
P = py.list({int32(1), int32(2), int32(3), int32(4)})P =
Python list with values:
[1, 2, 3, 4]
Use string, double or cell function to convert to a MATLAB array.
显示值的数值类型。
class(P{1})ans = 'py.int'
将 P 转换为 MATLAB 元胞数组。
cP = cell(P);
将元胞数组转换为 double 类型的 MATLAB 数组。
A = cellfun(@double,cP)
A = 1×4
1 2 3 4
读取嵌套 list 类型的元素
以下代码访问包含 list 元素的 Python list 变量的元素。假设您有此 list。
matrix = py.list({{1, 2, 3, 4},{'hello','world'},{9, 10}});显示元素 'world',它位于索引 (2,2) 处。
disp(char(matrix{2}{2}))world
显示 Python 元素的步进范围
如果您使用切片来访问 Python 对象的元素,Python 中的格式是 start:stop:step。在 MATLAB 中,语法形式为 start:step:stop。
li = py.list({'a','bc',1,2,'def'});
li(1:2:end)ans =
Python list with values:
['a', 1.0, 'def']
Use string, double or cell function to convert to a MATLAB array.