matlab中的dislist,在 MATLAB 中使用 Python list 变量

调用接受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]

7

显示一个元素。

P{2}

ans =

Python str with no properties.

R2016b

对 Python 列表进行索引

使用 MATLAB 索引显示列表中的元素。例如,显示 list 中的最后一个元素。MATLAB 返回一个 Python list。

P(end)

ans =

Python list with no properties.

['R2020a']

您也可以在 for 循环中循环访问该列表。

for n = P

disp(n{1})

end

Python str with no properties.

R2014b

Python str with no properties.

R2016b

Python str with no properties.

R2017b

Python str with no properties.

R2018b

Python str with no properties.

R2019a

Python str with no properties.

R2019b

Python str with no properties.

R2020a

将 Pythonlist类型转换为 MATLAB 类型

以下代码使用 MATLAB 变量显示 list P 中的名称。调用 cell 以转换该列表。该列表由 Python 字符串组成,因此调用 char 函数来转换元胞数组的元素。

cP = cell(P);

每个元胞元素名称均为一个 Python 字符串。

class(cP{1})

ans =

'py.str'

使用 char 函数将 Python 字符串转换为 MATLAB 数据。

cellP = cellfun(@char,cell(P),'UniformOutput',false);

显示名称。

for n = 1:numel(cP)

disp(cellP{n})

end

R2014b

R2016b

R2017b

R2018b

R2019a

R2019b

R2020a

在 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 no properties.

[1, 2, 3, 4]

显示值的数值类型。

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 no properties.

['a', 1.0, 'def']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值