简体   繁体   中英

How do I calculate a ratio for values within a dictionary?

Say I have a dictionary like so:

d = {1.0: 11, 2.0: 3, 3.0: 7}

I need to calculate the ratio of each value and the following value (k+1), then divide the sum of all ratios calculated by the number of ratios calculated, in this case, 2. If interested, this is for calculating a ' bifurcation ratio ' in stream stats.

expected output:

  • r1 = 11/3 = 3.67
  • r2 = 3/7 = 0.43

sum of ratios = 3.67 + 0.43 = 4.1 solution = 4.1 / 2 = 2.05

d = {1.0: 11, 2.0: 3, 3.0: 7}

ratio_values = list(d.values())

count = len(ratio_values) - 1
ratio_sum = 0

for i in range(len(ratio_values) - 1):
    #adds the ratio between two consecutive values to the total sum
    ratio_sum += ratio_values[i]/ratio_values[i+1]

print(ratio_sum/count)
import numpy as np

arr = np.array(list(d.values()))
arr

ans = 0
ratios = []
for i in range(1, len(arr)):
    ratios.append(arr[i-1]/arr[i])
ans = sum(ratios)/len(ratios)
d = {1.0: 11, 2.0: 3, 3.0: 7}
d = list(d.values())

ratios = []
solution = 0.0

per = d[0]
for v in d[1:]:
    ratios.append(per/v)
    per = v

solution = sum(ratios)/len(ratios)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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