【问题标题】:Python list comprehension with conditional and double for loop syntax error带有条件和双重for循环语法错误的Python列表理解
【发布时间】:2016-05-29 18:06:50
【问题描述】:

当所述“实际”元素等于 1(“真阳性”的数量)时,我正在尝试计算列表中“预测”中的元素等于“实际”列表中相应元素的次数。

这是我的代码:

def F_approx(predicted, actual):
   est_tp = np.sum([int(p == a) if a for p in predicted for a in actual])
   est_fn = np.sum([int(p !=a) if a for p in predicted for a in actual])
   est_recall = est_tp / (est_tp + est_fn)
   pr_pred_1 = np.sum([int(p == 1) for p in predicted]) / len(predicted)
   est_f = np.power(est_recall, 2) / pr_pred_1
   return(est_f)

这在 我的 眼中看起来是正确的,但我得到一个错误:

    File "<ipython-input-17-3e11431566d6>", line 2
       est_tp = np.sum([int(p == a) if a for p in predicted for a in actual])
                                           ^ 
    SyntaxError: invalid syntax

感谢您的帮助。

【问题讨论】:

    标签: python syntax-error list-comprehension


    【解决方案1】:

    if 循环表达式之后:

    [int(p == a) for p in predicted for a in actual if a]
    

    但是,看起来你真的想zip 这些一起:

    [int(p == a) for p, a in zip(predicted, actual)]
    

    【讨论】:

    • 有趣,谢谢。我刚刚阅读了来自stackoverflow.com/questions/17321138/… 的答案,这似乎暗示了相反的情况(至少对于 if else 情况)。为什么它在那里工作而不在这里工作?
    • 没关系,我可以回答我自己的问题。这个例子是一个过滤器,另一个不是。
    • 列表推导具有以下语法(大约):[expression for var in loop_expression if filter_expression]。这些表达式几乎可以是任何东西——包括具有以下形式的“条件表达式”:expression if conditional else conditional。请注意,else 是创建条件表达式所必需的。
    • @HudsonCooper -- 另请注意,如果 predictedactualnp.ndarray,您可以这样做:np.sum(predicted == array) 作为快捷方式 :-)
    【解决方案2】:

    if 放在列表推导的末尾

    [int(p == a) for p in predicted for a in actual if a]
    

    作为旁注,您可以使用您的特定构造添加三元运算并在您的列表理解中添加一个 else

    [int(p == a) if a else '' for p in predicted for a in actual if a]
    

    在列表解析的末尾添加 else 将抛出 SyntaxError

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 2021-08-22
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2012-09-29
      • 2023-03-11
      相关资源
      最近更新 更多