如何更改 IF 陳述句?我只得到無效的語法
predicted_sentiment = [if score < 0 then 'Negative', if score == 0 then 'Neutral' if score > 0 then 'Positive' for score in sentiment_polarity]
uj5u.com熱心網友回復:
你可能想要:
predicted_sentiment = [
('Negative' if score < 0 else 'Neutral' if score == 0 else 'Positive')
for score in sentiment_polarity
]
uj5u.com熱心網友回復:
您可以使用 lambda 來提高可讀性(有點主觀)并簡化測驗方式(更客觀)
>>> 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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/469414.html
上一篇:洗掉其他;如果怎么辦?