【发布时间】:2021-03-27 03:43:10
【问题描述】:
这个 python 代码不起作用。
为什么?
任何替代代码?
谢谢!
def suppress(D, threshold):
return {i:0 if x < threshold else i:x for (i, x) in D.items()}
【问题讨论】:
标签: python dictionary-comprehension
这个 python 代码不起作用。
为什么?
任何替代代码?
谢谢!
def suppress(D, threshold):
return {i:0 if x < threshold else i:x for (i, x) in D.items()}
【问题讨论】:
标签: python dictionary-comprehension
条件表达式是表达式,它们需要两个不同的表达式来计算一个值,
<expression 1> if <boolean expression> else <expression 2>
但i:0 不是表达式,它是字典显示的部分(这是一个表达式)。但就其本身而言,它只是一个语法错误。
你想要:
{i: <conditional expression> for (i, x) in D.items()}
或者更完整,
{i: 0 if x < threshold else x for (i, x) in D.items()}
【讨论】: