# 在 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. ```

```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] 9 ```

`P{2}`
```ans = Python str with no properties. R2016b ```

### 对 Python 列表进行索引

`P(end)`
```ans = Python list with no properties. ['R2021a'] ```

```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 Python str with no properties. R2020b Python str with no properties. R2021a ```

### 将 Python `list` 类型转换为 MATLAB 类型

`cP = cell(P);`

`class(cP{1})`
```ans = 'py.str' ```

`mlP = string(cell(P));`

```for n = 1:numel(cP) disp(mlP{n}) end```
```R2014b R2016b R2017b R2018b R2019a R2019b R2020a R2020b R2021a ```

### 在 MATLAB 中使用 Python 数值类型列表

Python `list` 包含任何类型的元素，并且可以包含混合类型的元素。以下代码中使用的 MATLAB `double` 函数假设 Python `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);`

`A = cellfun(@double,cP)`
```A = 1×4 1 2 3 4 ```

### 读取嵌套 `list` 类型的元素

`matrix = py.list({{1, 2, 3, 4},{'hello','world'},{9, 10}});`

`disp(char(matrix{2}{2}))`
```world ```

### 显示 Python 元素的步进范围

```li = py.list({'a','bc',1,2,'def'}); li(1:2:end)```
```ans = Python list with no properties. ['a', 1.0, 'def'] ```