python - 为什么在这段代码中可以引用 'r'变量?

标签 python

我正在阅读某人的代码如下,我有两个问题:
1) 'r.message' 中的 'r' 在哪里?它之前没有定义。
2) 对于这两行:

for r in intent_results
if r.intent_target != r.intent_prediction

if 语句没有缩进,也没有报错,这是为什么呢?

def collect_nlu_errors(intent_results, errors_filename):
    """Log messages which result in wrong predictions and save them to file"""

    errors = [
        {
            "text": r.message,
            "intent": r.intent_target,
            "intent_prediction": {
                "name": r.intent_prediction,
                "confidence": r.confidence,
            },
        }
        for r in intent_results
        if r.intent_target != r.intent_prediction
    ]

    if errors:
        utils.write_json_to_file(errors_filename, errors)
        logger.info("Model prediction errors saved to {}.".format(errors_filename))
        logger.debug(
            "\n\nThese intent examples could not be classified "
            "correctly: \n{}".format(errors)
        )
    else:
        logger.info("Your model made no errors")

最佳答案

第一个问题:

这是 Python 内联列表理解的示例。为了解释这是做什么的,这里有一个更简单的例子:

first_names = [person['first_name'] for person in people]

对于表单中的人员列表

people = [{'first_name': "John", 'last_name': "Doe"}, {'first_name': "Jane", 'last_name': "Doe"}]

以上将返回一个列表

['Jane', 'John']

这是在 PEP202 中介绍的.这是制作可读但简洁的代码的好方法(假设它没有被滥用)。

第二个问题:

它看起来缩进正确。只要预先定义了 errors,您就不会得到 NameError。

关于python - 为什么在这段代码中可以引用 'r'变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57365080/

相关文章:

python - 如何生成现在进行时 - 动词的 ING 形式?

python - 自动调整 tkinter 窗口大小以适应所有小部件

python - 使用 Azure-Monitoring-libraries-for-python 监视 Azure-Monitor 中的 azure-resources 并获取这些指标

python - 'RepeatedCompositeContainer' 类型的对象不是 JSON 可序列化的

python - 行的循环和 XLSXwriter 格式

python - 相对于另一个列表追加时,条件语句不起作用

python - Django Rest 框架 token 认证

python - Pandas 自定义函数来查找是否是第 1 天、第 2 天等星期一、星期二等 - 欢迎所有建议

python - 具有一个日期和三个不同值的数据框 : how can I get the one in the middle?

python - 有中英翻译API服务吗?