Home > Software design >  Make sume of specific value of 2d arrays
Make sume of specific value of 2d arrays

Time:02-26

No values here. Closing this!!

CodePudding user response:

Assuming all ranges are exclusive, that is, no range overlaps another range, you could iterate over this 2D array and reduce to a dict:

from collections import defaultdict

data = [['Less than $40K', '0.569'], ['$60K - $80K' ,'0'], ...]

res = defaultdict(float)

for tup in data:
  rng, amt = tup
  res[rng]  = float(amt)

print(list(res.items()))
[('Less than $40K', 4.3919999999999995), ('$60K - $80K', 0.545), ('$80K - $120K', 0.625), ('Unknown', 0.6659999999999999), ('$40K - $60K', 0.37200000000000005), ('$120K  ', 0.4)]

CodePudding user response:

Create a dictionary that uses the first column value in your avgUtilArray as key. We just check if there is a value stored for that key already, in which case, we add to it. Otherwise, we make a new entry in dictionary with that key.

output = {}

for row in avgUtilArray:
    key = row[0]
    value = float(row[1])
    if key in output:
        output[key]  = value
    else:
        output[key] = value

print(output)

The output:

{'Less than $40K': 4.3919999999999995, '$60K - $80K': 0.545, '$80K - $120K': 0.625, 'Unknown': 0.6659999999999999, '$40K - $60K': 0.37200000000000005, '$120K  ': 0.4}

Also, I corrected your 2d list for you:)

avgUtilArray = [

['Less than $40K', '0.569'],
['$60K - $80K', '0'],
['Less than $40K', '0.3'],
['$80K - $120K', '0.045'],
['Unknown', '0.091'],
['$40K - $60K', '0'],
['$80K - $120K', '0.056'],
['$60K - $80K', '0'],
['Less than $40K', '0.595'],
['$120K  ', '0.097'],
['$80K - $120K', '0.066'],
['$60K - $80K', '0.216'],
['$120K  ', '0.031'],
['Less than $40K', '0.316'],
['Less than $40K', '0.045'],
['$60K - $80K', '0.065'],
['$80K - $120K', '0.051'],
['Less than $40K', '0.342'],
['$80K - $120K', '0.041'],
['Unknown', '0'],
['$40K - $60K', '0'],
['$40K - $60K', '0'],
['Less than $40K', '0'],
['$80K - $120K', '0'],
['Unknown', '0'],
['Unknown', '0.575'],
['$60K - $80K', '0.032'],
['Less than $40K', '0.505'],
['$120K  ', '0.05'],
['$80K - $120K', '0.366'],
['Less than $40K', '0.182'],
['Less than $40K', '0.332'],
['Less than $40K', '0.194'],
['$40K - $60K', '0.058'],
['Less than $40K', '0.228'],
['$120K  ', '0.038'],
['Less than $40K', '0.155'],
['Less than $40K', '0.371'],
['$60K - $80K', '0'],
['Less than $40K', '0.258'],
['$120K  ', '0.036'],
['$120K  ', '0.148'],
['$60K - $80K', '0.037'],
['$120K  ', '0'],
['Unknown', '0'],
['$60K - $80K', '0.195'],
['$60K - $80K', '0'],
['$40K - $60K', '0.229'],
['$40K - $60K', '0.085'],
['Unknown', '0']
]
  • Related