このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。
MATLAB での Python dict
変数の使用
この例では、MATLAB® で Python® のディクショナリ (dict
) 変数を使用する方法を説明します。
dict
入力引数を取る Python 関数を呼び出すには、変数 py.dict
を作成します。dict
を MATLAB 変数に変換するには、関数 struct
を呼び出します。
Python dict
変数の作成
dict
変数を作成し、Python 関数に渡します。
studentID = py.dict(Robert=357,Mary=229,Jack=391)
studentID = Python dict with no properties. {'Robert': 357.0, 'Mary': 229.0, 'Jack': 391.0}
あるいは、MATLAB 構造体を作成し、dict
変数に変換します。
S = struct("Robert",357,"Mary",229,"Jack",391); studentID = py.dict(S)
studentID = Python dict with no properties. {'Robert': 357.0, 'Mary': 229.0, 'Jack': 391.0}
MATLAB での Python dict
型の使用
Python 関数から返された dict
型を MATLAB 変数に変換するには、struct
を呼び出します。
メニュー項目と価格を order
という名前の dict
オブジェクトに返す Python 関数があるとします。このコードを MATLAB で実行するには、次の変数を作成します。
order = py.dict(soup=3.57,bread=2.29,bacon=3.91,salad=5.00)
order = Python dict with no properties. {'soup': 3.57, 'bread': 2.29, 'bacon': 3.91, 'salad': 5.0}
order
を MATLAB 変数に変換します。
myOrder = struct(order)
myOrder = struct with fields:
soup: 3.5700
bread: 2.2900
bacon: 3.9100
salad: 5
MATLAB 構文を使用してベーコンの価格を表示します。
price = myOrder.bacon
price = 3.9100
Python 構文を使用してベーコンの価格を表示します。変数 price
の型は double であり、MATLAB で使用することができます。
price = order{"bacon"}
price = 3.9100
ディクショナリには、キーと値のペアがあります。Python 関数 keys
を使用して、変数 order
にあるメニュー項目を表示します。
keys(order)
ans = Python dict_keys with no properties. dict_keys(['soup', 'bread', 'bacon', 'salad'])
Python 関数 values
を使用して、すべての価格を表示します。
values(order)
ans = Python dict_values with no properties. dict_values([3.57, 2.29, 3.91, 5.0])
Python メソッドへの dict
引数の受け渡し
Python dict
クラスには update
メソッドがあります。このコードを実行するには、患者とテスト結果の dict
変数を作成します。
patient = py.dict(name="John Doe", ... test1= [], ... test2= [220.0, 210.0, 205.0], ... test3= [180.0, 178.0, 177.5]);
患者の名前を MATLAB string に変換します。
string(patient{"name"})
ans = "John Doe"
update
メソッドを使用して、test1
の結果を更新し表示します。
update(patient,py.dict(test1=[79.0, 75.0, 73.0])) P = struct(patient); disp(["test1 results for "+string(patient{"name"})+": "+num2str(double(P.test1))])
test1 results for John Doe: 79 75 73