Use Pythonlist
Variables in MATLAB
This example shows how to use Python®list
变量在马TLAB®.
To call a Python function that takes alist
输入参数,创建一个py.list
variable. To convert a list to a MATLAB variable, call thecell
功能,然后调用列表中每个元素的适当转换功能。
Call Python Function That Takeslist
Input Arguments
The Pythonlen
function returns the number of items in a container, which includes alist
目的。
py.help('len')
Help on built-in function len in module builtins: len(obj, /) Return the number of items in a container.
Callos.listdir
to create a Pythonlist
命名的程序P
.
P = py.os.listdir(“ C:\ Program Files \ Matlab”);班级(P)
ans = 'py.list'
Display the number of programs.
py.len(p)
ans = python int具有属性:分母:[1×1 py.int]图像:[1×1 py.int]分子:[1×1 py.int]真实:[1×1 py.int] 9
Display one element.
p {2}
ans = Python str with no properties. R2016b
Index into Python List
Use MATLAB indexing to display elements in a list. For example, display the last element in thelist
. MATLAB returns a Pythonlist
.
P(end)
ans = Python list with no properties. ['R2021a']
You also can iterate over the list in afor
loop.
forn = 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
Convert Pythonlist
类型对MATLAB类型
This code displays the names inlist
P
using MATLAB variables. Callcell
to convert the list. The list is made up of Python strings, so call thechar
function to convert the elements of the cell array.
cP = cell(P);
每个单元格元素名称都是一个python字符串。
class(cP{1})
ans ='py.str'
将Python字符串转换为MATLAB数据。
mlP = string(cell(P));
Display the names.
forn = 1:numel(cP) disp(mlP{n})end
R2014b R2016b R2017b R2018b R2019a R2019b R2020a R2020b R2021a
Use Python List of Numeric Types in MATLAB
pythonlist
contains elements of any type and can contain elements of mixed types. The MATLABdouble
此代码中使用的功能假设Python的所有元素list
are numeric.
Suppose that you have a Python function that returns alist
整数P
. To run this code, create the variable with these values.
p = py.list({int32(1),int32(2),int32(3),int32(4)})
p =没有属性的python列表。[1,2,3,4]
Display the numeric type of the values.
class(P{1})
ans ='py.int'
ConvertP
to a MATLAB cell array.
cP = cell(P);
将单元格数组转换为MATLAB阵列double
.
A = cellfun(@double,cP)
A =1×41 2 3 4
Read Element of Nestedlist
Type
This code accesses an element of a Pythonlist
variable containinglist
elements. Suppose that you have thislist
.
matrix = py.list({{1, 2, 3, 4},{'hello','世界'},{9, 10}});
显示元素'世界'
,索引(2,2)
.
disp(char(matrix{2}{2}))
world
Display Stepped Range of Python Elements
If you use slicing to access elements of a Python object, the format in Python isstart:stop:step
. In MATLAB, the syntax is of the form开始:步骤:停止
.
li = py.list({'a','bc',1,2,'def'}); li(1:2:end)
ans = Python list with no properties. ['a', 1.0, 'def']