IF 语句无效语法消息

IF statement invalid syntax message

如何更改 IF 语句?我只得到无效语法

predicted_sentiment = [if score < 0 then 'Negative', if score == 0 then 'Neutral' if score > 0 then 'Positive' for score in sentiment_polarity] 

你可能想要:

predicted_sentiment = [
    ('Negative' if score < 0 else 'Neutral' if score == 0 else 'Positive') 
    for score in sentiment_polarity
]

您可以使用 lambda 来提高可读性(有点主观)并简化测试方式(更多 objective)

>>> c = lambda x: 'Negative' if x < 0 else 'Neutral' if x == 0 else 'Positive'
>>> c(2)
'Positive'
>>> c(-2)
'Negative'
>>> c(0)
'Neutral'
>>> sentiment_polarity = [1, 0, -2, 3, -4]
>>> predicted_sentiment = [c(s) for s in sentiment_polarity]
>>> predicted_sentiment
['Positive', 'Neutral', 'Negative', 'Positive', 'Negative']

编辑

你也可以这样使用numpy.sign()

c = lambda x: ['Negative', 'Neutral', 'Positive'][numpy.sign(x)+1]