在for循环中划分并找到最大值:Python

时间:2016-12-07 00:49:02

标签: python

我有以下循环:

for key, value in sentiment_dict.items():
    print ("%s: %s" % (key, value))

打印出来

Bullish: 9
Bearish: 1

我想将较小的值除以较大的值(1/9),在这种情况下"看涨"虽然更大但可能反过来。之后我想打印出来

"There is a %s probability that the stock is %s" % (percentage, text with smaller n)
#In this case it would be
"There is a .1111 probability that the stock is Bearish"

在这种情况下我应该使用哪些函数或方法?

编辑:如果有帮助,这是代码的其余部分

import requests
link= 'https://api.stocktwits.com/api/2/streams/symbol/'+input+'.json'
a=requests.get(link)
a=a.json()

from collections import Counter
sentiment_dict = Counter()
for message in a['messages']:
    if 'entities' in message:
        if 'sentiment' in message['entities']:
            sentiment = message['entities']['sentiment']
            if sentiment is not None:
               sentiment = sentiment['basic']
               sentiment_dict[sentiment] += 1
for key, value in sentiment_dict.items():
print ("%s: %s" % (key, value))

2 个答案:

答案 0 :(得分:1)

  

我想将较小的值除以较大的值

min()max()built in functions

min(a,b) / max(a,b)

答案 1 :(得分:0)

尝试:

min_value = min(sentiment_dict.values())
max_value = max(sentiment_dict.values())
min_key = {value:key for (key, value) in sentiment_dict.items()}[min_value]

print("There is a %s probability that the stock is %s" % (min_value/max_value, min_key))

第三行将反转字典以获取与最小值对应的键。