主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

使用 Python 字典数据计算胜率

支持的平台:Windows®、Linux®Mac

此示例说明如何创建一个 Python® 应用程序,在 Python 和 MATLAB® 之间传递存储在字典中的统计数据。MATLAB 函数根据运动队的胜利、失败和平局来计算其胜率。Python 应用程序创建字典数据,调用 MATLAB 函数并显示结果。当在 MATLAB 和 Python 之间传递数据时,数据会转换为等效的数据类型。有关数据类型及其转换的完整列表,请参阅在 MATLAB 和 Python 之间传递数据

前提条件

验证您所安装的 Python 版本是否与 MATLAB Compiler SDK™ 兼容。有关详细信息,请参阅MATLABCompiler SDK Python 目标要求

目标计算机需要 MATLAB Runtime 来运行已部署的 MATLAB 代码。您可以将 MATLAB Runtime 包含在 Python 包的安装程序中,也可以单独安装它。有关详细信息,请参阅下载并安装 MATLAB Runtime

MATLAB 中创建函数

编写一个名为 insertWinPercentage 的 MATLAB 函数,用于访问存储在字典对象中的数据。

function outputArg = insertWinPercentage(stats)
% Check if the necessary keys exist
if isKey(stats, "Wins") && isKey(stats, "Losses") && isKey(stats, "Ties")
    % Calculate the win percentage
    wins = stats("Wins");
    gamesPlayed = wins + stats("Losses") + stats("Ties");
    winPercent = (wins / gamesPlayed) * 100;
    
    % Add the win percentage to the dictionary
    stats("WinPercentage") = round(winPercent,2);
else
    % The necessary data is not available
    disp("Required data (Wins, Losses, and/or Ties) is missing from the dictionary.");
end

outputArg = stats;
end

在此示例中,函数采用包含统计数据的字典对象 stats,计算并添加获胜百分比条目,然后输出修改后的字典对象。

创建 Python

使用 Python 包编译器compiler.build.pythonPackage 函数构建 Python 包。使用 insertWinPercentage.m 文件进行编译并将包命名为 accessDict

例如,如果您使用的是 compiler.build.pythonPackage,请输入:

buildResults = compiler.build.pythonPackage( ...
'insertWinPercentage.m', ...
'PackageName','accessDict');

有关详细信息,请参阅生成 Python 包并编译 Python 应用程序

编写 Python 应用程序代码

用 Python 为调用 MATLAB 函数的名为 modifyDict 的应用程序编写代码。此示例应用程序显示修改前后的字典数据。

#!/usr/bin/env python
"""
Sample that uses the accessDict package you created using
MATLAB Compiler SDK. See the MATLAB Compiler SDK 
documentation for more information.
"""
import accessDict

# Import the matlab package only after you have imported 
# all MATLAB Compiler SDK generated Python packages.

import matlab

try:
    myaccessDict = accessDict.initialize()    
except Exception as e:
    print('Error initializing accessDict package\n:{}'.format(e))
    exit(1)
try:
    # Function to print the dictionary keys and values
    def print_dictionary(dct):    
        for key, val in dct.items():
            print("{} ({})".format(key, val))
    
    # Define keys and values for the dictionary    
    stats = {    
        'Wins': float(24),
        'Losses': float(8),
        'Ties': float(2),
        'AveragePoints': float(110.5),
        'HighestPointTotal': float(152)}
    
    # Convert stats to a matlab.dictionary, which is automatically
    # converted to a MATLAB dictionary when passed to MATLAB.
    m_stats = matlab.dictionary(stats)    
    
    #Print dictionary before and after modification
    print('Without win percentage:')
    print_dictionary(m_stats)

    newstats = myaccessDict.insertWinPercentage(m_stats)

    print('\nWith win percentage:')
    print_dictionary(newstats)

except Exception as e:
    print('Error occurred during program execution\n:{}'.format(e))
myaccessDict.terminate()

该应用程序执行以下操作:

  • 导入 accessDictmatlab 包。

  • accessDict 实例实例化为 myaccessDict

  • 将数据保存在名为 matlab.dictionarystats 对象中。

  • 调用 insertWinPercentage 包中的 accessDict 方法来创建名为 newstats 的字典的修改副本。

  • 使用辅助函数 stats 显示 newstatsprint_dictionary 的内容。

  • 使用 try 模块来捕获并处理任何异常。

安装并运行 Python

在目标计算机上,安装生成的 Python 包。有关详细信息,请参阅安装并导入 MATLAB Compiler SDK Python 包

在系统命令提示符中,导航到包含生成文件的文件夹并安装 Python 包。

python -m pip install .

运行该应用程序。

python modifyDict.py

该应用程序生成以下输出。

Without win percentage: 
Wins (24.0) 
Losses (8.0) 
Ties (2.0) 
AveragePoints (110.5) 
HighestPointTotal (152.0) 
 
With win percentage: 
Wins (24.0) 
Losses (8.0) 
Ties (2.0) 
AveragePoints (110.5) 
HighestPointTotal (152.0) 
WinPercentage (70.59) 

另请参阅

主题