有人可以建议一些优化以下代码的方法吗?
第一种方法
board =[
{"Pakistan": 123},
{"Pakistan": 27},
{"India": 3},
{"India": 71},
{"Australia": 31},
{"India": 22},
{"Pakistan": 81},
{"India": 171},
{"India": 171},
]
country = {}
for item in board:
for team,value in item.items():
try: country[team].append(value)
except KeyError: country[team] = [value]
print(country)
avg={}
for key, value in country.iteritems():
avg[key]= sum(value)/len(value)
print(avg)
def maximum(team):
d3={v:k for k,v in team.items()}
return d3[max(d3)]
print(maximum(avg))
第二种方法
avgDict = {}
for k,v in [(key,d[key]) for d in board for key in d]:
if k not in avgDict: avgDict[k]=[v]
else: avgDict[k].append(v)
print(avgDict)
只需获取名称和分数列表。
先谢谢。
答案 0 :(得分:0)
这是清洁国家和平均水平的部分解决方案:
import numpy as np
keys = [k for d in board for k in d.keys()]
values = [v for d in board for k,v in d.items()]
avg = int(np.mean(values))
答案 1 :(得分:0)
您可以将var a = "23 years 08 months 12 days";
var b = "5 years 8 months 1 days";
var res = a.substring(0, a.indexOf('months')) + 'months';
console.log(res);
var res = b.substring(0, b.indexOf('months')) + 'months';
console.log(res);
与字典/列表推导结合使用。通常,这些方法应该更有效。
collections.defaultdict
<强>结果强>
from collections import defaultdict
d = defaultdict(list)
for i in board:
for k, v in i.items():
d[k].append(v)
d_avg = {k: sum(v)/len(v) for k, v in d.items()}
max_country = [k for k in d_avg if d_avg[k] == max(d_avg.values())]
答案 2 :(得分:0)
使用pandas可能会更有效率
import pandas as pd
items = ((k,v) for d in board for k,v in d.items())
df = pd.DataFrame(items)
df.groupby(0).mean()
答案 3 :(得分:0)
使用pandas
:
import pandas as pd
boardf = pd.DataFrame(board)
finaldict = {}
for country, values in boardf.items():
finaldict[country] = values.dropna().values.tolist()
print(finaldict)
print(boardf.mean().to_dict())
print(boardf.max().sort(inplace=False, ascending=False).index[0])
输出结果为:
{'Australia': [31.0], 'Pakistan': [123.0, 27.0, 81.0], 'India': [3.0, 71.0, 22.0, 171.0, 171.0]}
{'Australia': 31.0, 'Pakistan': 77.0, 'India': 87.599999999999994}
India