I have a dictionary where each key is mapped to a value of lists (specifically, coordinates):
3 -> [['7', '16'], ['72', '48'], ['36', '52'], ['75', '36'], ['52', '28'], ['76', '44'], ['56', '35'], ['15', '21'], ['88', '32'], ['61', '34'], ['94', '12'], ['71', '59'], ['25', '16'], ['62', '1'], ['16', '32'], ['71', '4'], ['42', '32'], ['37', '49'], ['49', '34'], ['3', '5'], ['49', '40'], ['40', '53'], ['57', '48'], ['10', '9'], ['97', '3']]
2 -> [['71', '84'], ['32', '74'], ['51', '85'], ['55', '96'], ['34', '64'], ['76', '75'], ['54', '100'], ['60', '85'], ['40', '78'], ['78', '91'], ['100', '98'], ['42', '77'], ['39', '60'], ['38', '77'], ['66', '67'], ['66', '76'], ['86', '68']]
1 -> [['11', '69'], ['10', '74'], ['10', '75'], ['14', '77'], ['2', '60'], ['14', '99'], ['10', '60'], ['8', '87']]
For each key, I need to average all of the X coordinates and all of the Y coordinates, but I haven't been able to figure out how to iterate through each key and average each value.
Any help would be much appreciated!
CodePudding user response:
You could use dict.items()
function to iterate on the keys and values, and just calculate the average of your Xs and Ys.
Here's a sample code:
def avg(list):
return sum(list) / len(list)
for k, v in dict.items():
x_sum = avg([int(e[0]) for e in v])
y_sum = avg([int(e[1]) for e in v])
Of course you need to cast the strings into integers (or floats) since they are strings for you.
CodePudding user response:
You can use zip() on the lists of coordinates to isolate all the Xs and Ys into separate lists that you can then process to compute the average:
D = {
3:[['7', '16'], ['72', '48'], ['36', '52'], ['75', '36'], ['52', '28'], ['76', '44'], ['56', '35'], ['15', '21'], ['88', '32'], ['61', '34'], ['94', '12'], ['71', '59'], ['25', '16'], ['62', '1'], ['16', '32'], ['71', '4'], ['42', '32'], ['37', '49'], ['49', '34'], ['3', '5'], ['49', '40'], ['40', '53'], ['57', '48'], ['10', '9'], ['97', '3']],
2:[['71', '84'], ['32', '74'], ['51', '85'], ['55', '96'], ['34', '64'], ['76', '75'], ['54', '100'], ['60', '85'], ['40', '78'], ['78', '91'], ['100', '98'], ['42', '77'], ['39', '60'], ['38', '77'], ['66', '67'], ['66', '76'], ['86', '68']],
1:[['11', '69'], ['10', '74'], ['10', '75'], ['14', '77'], ['2', '60'], ['14', '99'], ['10', '60'], ['8', '87']]
}
A = {k:[sum(map(float,x))/len(v),sum(map(float,y))/len(v)]
for k,v in D.items() for x,y in [zip(*v)]}
print(A)
{3: [50.44, 29.72], 2: [58.11764705882353, 79.70588235294117], 1: [9.875, 75.125]}
Note that you should make an effort to store numeric data as the proper numeric types earlier so that you don't have to convert it from string everywhere else in the rest of your program
Once your data is in a usable numeric type, the code to compute the averages becomes simpler/clearer:
D = {k:[ [float(x),float(y)] for x,y in v] for k,v in D.items() }
A = {k:[sum(x)/len(v),sum(y)/len(v)] for k,v in D.items() for x,y in [zip(*v)]}