Main Content

在 MATLAB 中使用 Python tuple 变量

此示例说明如何在 MATLAB® 中使用 Python® tuple 变量。

tuple 转换为 MATLAB 变量

要将 tuple 转换为 MATLAB 元胞数组,请调用 cell 函数。

pStudent = py.tuple({'Robert',19,'Biology'})
pStudent = 
  Python tuple with values:

    ('Robert', 19.0, 'Biology')

    Use string, double or cell function to convert to a MATLAB array.

S = cell(pStudent)
S=1×3 cell array
    {1×6 py.str}    {[19]}    {1×7 py.str}

读取 tuple 中的元素

使用 MATLAB 索引显示 tuple 中的元素。例如,显示 pStudent 的前两个元素。MATLAB 返回一个 tuple 变量。

pStudent(1:2)
ans = 
  Python tuple with values:

    ('Robert', 19.0)

    Use string, double or cell function to convert to a MATLAB array.

显示一个元素。MATLAB 返回一个 Python 数据类型的元素。

pStudent{3}
ans = 
  Python str with no properties.

    Biology

创建包含单个元素的 tuple

用单个元素创建一个 tuple 变量。MATLAB 对包含一个元素的 tuple 显示尾部逗号。

subject = py.tuple({'Biology'})
subject = 
  Python tuple with values:

    ('Biology',)

    Use string, double or cell function to convert to a MATLAB array.