将列表中的元组转换为字典并计算频率

时间:2019-05-29 11:47:41

标签: python dictionary

三个朋友(迈克,约翰和汤姆)以厘米为单位测量了他们的跳跃长度。我们已将其跳转结果存储在模板代码中。创建一个名为avg_results的字典,该字典将名称存储为键,并将其平均跳转长度存储为值。

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

我只知道如何计算每个度量的总和,但是我不知道如何迭代并获取每个计数。

for jump in jumps:
  name,length=jump
  dict_results[name]=dict_results.get(name,0)+length

4 个答案:

答案 0 :(得分:2)

代码:

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

res = {}
for name, length in jumps:
    res[name] = [length] if name not in res else res[name] + [length]
avg_results = {k: sum(v) / len(v) for k, v in res.items()}

输出:

{'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}

答案 1 :(得分:1)

您是否尝试过与collections.defaultdict(list)进行分组,然后将平均值除以sum()除以len()

from collections import defaultdict

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

d = defaultdict(list)
for name, length in jumps:
    d[name].append(length)

avg = {k: sum(v) / len(v) for k, v in d.items()}

print(avg)
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}

您还可以使用statistics.mean()来获取平均值:

from statistics import mean

avg = {k: mean(v) for k, v in d.items()}

print(avg)
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}

答案 2 :(得分:1)

您可以尝试:

dict_results = {}
jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]
for jump in jumps:
    name, length = jump
    if name in dict_results:
        dict_results[name].append(length)
    else:
        dict_results[name] = [length]

for key, val in dict_results.items():
    dict_results[key] = sum(val) / len(val)

print(dict_results)

输出

{'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}

答案 3 :(得分:0)

以下是使用基于this答案的字典的一种可能的解决方案

dct = {}

for i, j in jumps:
    group = dct.get(i, [])
    group.append(j)
    dct[i] = group

avg_results = {k:sum(v)/len(v) for k, v in dct.items()}
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}