Trying To Find The Average Of Multiple Values In A Dictionary
Solution 1:
You already store a count with each list of values; simply loop over the dictionary items (key-value) pairs and use the last element of the value lists:
for key, values in d.items():
avg = [v / values[-1] for v in values[:-1]]
print(key, *avg)
This uses the last element of each values
list as the row count, and uses a list comprehension to produce an average value for each of your columns.
Some other remarks:
you evidently have a CSV file; consider using the
csv
module instead.you never called the
f.close()
method; you merely referenced it.However, you should consider using the file object as a context manager instead. The
with
statement ensures that the file is closed for you when the block is exited:withopen("iris.data", "r") as f: for line in f: line = line.rstrip('\n') ifnot line: continue
Solution 2:
You can convert the values to a list, then sum, and divide by the length of the list:
values = d.values()
average_value = sum(values) / len(values)
Since the values are lists, perhaps you can get the average for each list:
for v in d.values():
average_value = sum(v) / len(v)
Post a Comment for "Trying To Find The Average Of Multiple Values In A Dictionary"