简体   繁体   English

Python:避免使用.get('')重复

[英]Python: Avoid repetition with .get('')

I currently have the following lines of code where I write sentiment_score.get( over and over. Is there a better / smarter way to write that? 我目前有以下几行代码,一遍又一遍地写sentiment_score.get( 。是否有更好/更聪明的方式来编写它?

sentiment = detect_sentiment.get('Sentiment')
sentiment_score = detect_sentiment['SentimentScore']
mixed = sentiment_score.get('Mixed')
negative = sentiment_score.get('Negative')
neutral = sentiment_score.get('Neutral')
positive = sentiment_score.get('Positive')

Not as compact as @mohit-solanki 's solution, but more linter friendly: 不像@ mohit-solanki的解决方案那么紧凑,但是对棉绒更友好:

mixed, negative, neutral, positive = [
    sentiment_score.get(i) for i in [
      'Mixed', 'Negative', 'Neutral', 'Positive',
]]

...and more coder-friendly as well, IMHO ;-) ...以及对编码员更友好的恕我直言;-)

mixed, negative, neutral, positive = [detect_sentiment['SentimentScore'][key] for key in ['Mixed', 'Negative', 'Neutral', 'Positive']]

This is probably ugly but you can do this 这可能很难看,但您可以这样做

for name in ['Mixed', 'Negative', 'Neutral', 'Positive']:
    locals()[name.lower()] = sentiment_score.get(name)

locals() returns a dictionary containing the local scope docs locals()返回包含本地范围文档的字典

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM