I have a dictionary whereas the values are of string type. But I want to calculate the average per key whereas the empty string is a missing value. Here's my code just need a small twerk for it to work...with error : int() argument must be a string or a number, not 'list'
dic = {'E': ['1', '', '3'], 'M': ['2', '', '1']}
for k,n in dic.items():
k = [0]
n = [1]
D = {k: (int(n)) for k, n in dic.items() if n}
ave = {k:sum(D)/float(len(D))} if D else '-'
print ave
Expected output: {'E': 2, 'M': 1.5}
dic = {'E': ['1', '', '3'], 'M': ['2', '', '1']}
ave = dict()
for k in dic:
nonempty = [ float(v) for v in dic[k] if v != '' ]
ave[k] = sum(nonempty) / len(nonempty)
print ave
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.