dict matlab,在 MATLAB 中使用 Python dict 变量

创建 Python dict 变量

创建一个 dict 变量以传递给 Python 函数。pyargs 函数创建关键字参数。

studentID = py.dict(pyargs('Robert',357,'Mary',229,'Jack',391))

studentID =

Python dict with no properties.

{'Robert': 357.0, 'Mary': 229.0, 'Jack': 391.0}

或者,创建一个 MATLAB 结构体并将其转换为 dict 变量。

S = struct('Robert',357,'Mary',229,'Jack',391);

studentID = py.dict(S)

studentID =

Python dict with no properties.

{'Robert': 357.0, 'Mary': 229.0, 'Jack': 391.0}

在 MATLAB 中使用 Python dict 类型

要将从 Python 函数返回的 dict 类型转换为 MATLAB 变量,请调用 struct。

假设您有一个 Python 函数,它在名为 order 的 dict 对象中返回菜单项和价格。要在 MATLAB 中运行以下代码,请创建此变量。

order = py.dict(pyargs('soup',3.57,'bread',2.29,'bacon',3.91,'salad',5.00))

order =

Python dict with no properties.

{'soup': 3.57, 'bread': 2.29, 'bacon': 3.91, 'salad': 5.0}

将 order 转换为 MATLAB 变量。

myOrder = struct(order)

myOrder = struct with fields:

soup: 3.5700

bread: 2.2900

bacon: 3.9100

salad: 5

使用 MATLAB 语法显示培根的价格。

price = myOrder.bacon

price = 3.9100

使用 Python 语法显示培根的价格。变量 price 为双精度类型,可在 MATLAB 中使用。

price = order{'bacon'}

price = 3.9100

字典有成对的键和值。使用 Python keys 函数显示变量 order 中的菜单项。

keys(order)

ans =

Python dict_keys with no properties.

dict_keys(['soup', 'bread', 'bacon', 'salad'])

使用 Python values 函数显示所有价格。

values(order)

ans =

Python dict_values with no properties.

dict_values([3.57, 2.29, 3.91, 5.0])

将 dict 参数传递给 Python 方法

Python dict 类有一个 update 方法。要运行以下代码,请创建包含患者和检测结果的 dict 变量。

patient = py.dict(pyargs('name', 'John Doe', ...

'test1', [], ...

'test2', [220.0, 210.0, 205.0], ...

'test3', [180.0, 178.0, 177.5]));

将患者姓名转换为 MATLAB 字符串。

string(patient{'name'})

ans =

"John Doe"

使用 update 方法更新并显示 test1 的结果。

update(patient,py.dict(pyargs('test1',[79.0, 75.0, 73.0])))

P = struct(patient);

disp(['test1 results for '+string(patient{'name'})+": "+num2str(double(P.test1))])

test1 results for John Doe: 79 75 73

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值