gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:26:31 25 4
gpt4 key购买 nike

我正在阅读某人的代码如下,我有两个问题:
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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com