我正在使用 MATLAB 2014b 中的新功能,您可以直接从 matlab 调用 python 并在工作区中获取 python 对象(就像您已经能够使用 Java 很长时间一样)。我已经成功调用了一个函数并将字典放入工作区,但我一直在思考如何从中获取值。在这种情况下,我有一个充满字典的字典,所以我不能像在他们的例子中那样将它转换为 MATLAB 单元格。
所以一个具体的问题:如果我在 MATLAB 中有一个名为“A”的字典,我如何得到子字典 A['2'] ?
By consulting the MATLAB External Interfaces documentation, the Python dict type is essentially the same interface as a containers.Map. You need to use the values function to extract the value that you want for a certain key. As such, you would call values like so, given that your Python dictionary is stored in A and you want to use '2' as the key to index into your dictionary:
val = values(A, '2');
Run Code Online (Sandbox Code Playgroud)
As such, val would contain what the associated value is with the key of '2'. MATLAB also has the ability to use multiple keys and it would return multiple values - one per key. Therefore, you could also do something like this:
val = cell(values(A, {'1', '2', '3'}));
Run Code Online (Sandbox Code Playgroud)
val将是一个三元素元胞数组,其中每个元素都是您输入的关联键的值。您必须将 的输出转换values为cell数组,因为这通常是Python 中的列表。为了在 MATLAB 中使用这些结果,我们需要将其转换为cell.
因此,当您用作键val{1}时,将是字典输出。'1'同样,当您用作键等val{2}时,字典输出将是这样的。'2'
这里有一些针对对象的更多操作containers.Map。如果您想要字典中的所有键,请使用以下keys函数:
k = keys(A);
Run Code Online (Sandbox Code Playgroud)
如果您只是values单独使用字典,如下所示:
val = cell(values(A));
Run Code Online (Sandbox Code Playgroud)
它将生成存储在元胞数组中的字典中存在的每个键的所有值。
如果您想更新 Python 字典中的特定键,请使用以下update函数:
update(A,py.dict(pyargs('4',5.677)));
Run Code Online (Sandbox Code Playgroud)
在这里,我们使用字典A,并更新键值对,其中键是'4',新值是5.677。
| 归档时间: |
|
| 查看次数: |
2648 次 |
| 最近记录: |