Main Content

Access Elements inPythonContainer Types

To work with a Python®variable in MATLAB®, convert the Python object to a MATLAB array, and then index into the array as needed. You also can preserve the Python object without converting, for example, to pass the object to a Python method.

A Pythoncontaineris typically asequence类型(listortuple) or amapping类型(dict). In Python, use square brackets[]or theoperator.getitemfunction to access an element in the container. Scalarstringarguments can be used to index into the container.

Sequence Types

Python sequence types behave like MATLAB cell arrays.

Get a subsequence using smooth-parenthesis()indexing.

li = py.list({1,2,3,4}); res = li(2:3)
res = Python list with no properties. [2.0, 3.0]

Use curly braces{}to get the contents of the element.

res = li{1}
res = 1

Mapping Types

For mapping types, use curly braces with the Pythonkeyargument.

patient = py.dict(name="John Doe",billing=127); patient{"billing"}
ans = 127

Size and Dimensions

MATLAB displays information for your system.

p = py.sys.path; class(p)
ans = py.list

Index intop.

p(1) p{1}
ans = Python list with no properties. ['c:\\work'] ans = Python str with no properties. c:\work

Inspect dimensions.

len = length(p) sz = size(p)
len = 11 sz = 1 11

Array Support

MATLAB converts a sequence type into a1-by-Narray.

Use Zero-Based Indexing forPythonFunctions

Python uses zero-based indexing; MATLAB uses one-based indexing. When you call a Python function, such aspy.sys.path, the index value of the first element of a Python container,x, isint32(0). The index value for the last element isint32(py.len(x)-1).

Limitations to Indexing intoPythonObjects

You can access data in Python container objects, like lists and dictionaries, with index values, similar to referencing an element in a MATLAB matrix. There are, however, ways to index into matrices which are not supported for these Python types.

Indexing Features Not Supported in MATLAB

Use of square brackets,[].

Indexing into a container type that does not inherit fromcollections.Sequenceorcollections.Mapping.

Logical indexing.

Accessing data in a container with an arbitrary array of indices. An index must be of the formstart:step:stop.

Comma-separated lists.

numelfunction does not return number of array elements. Returns 1.

相关交货amples

More About