如何在python中查找列表中字典匹配键值的平均值

2024-09-24 00:29:53 发布

您现在位置:Python中文网/ 问答频道 /正文

[{"name": "thisisname1", "filebytestotal": 334632,"memorybytes": 5467234},    
{"name": "thisisname2", "filebytestotal": 2351, "memorybytes": 324523},    
{"name": "thisisname3", "filebytestotal": 2314651, "memorybytes": 2235},    
{"name": "thisisname1", "filebytestotal": 13432, "memorybytes": 546534},    
{"name": "thisisname1", "filebytestotal": 32342, "memorybytes": 341234}]

大家好,我试着找出如何为所有匹配的“name”值生成键filebytes和memorybytes的平均值。 我的问题是我不知道´我不知道如何通过总列表中的字典来搜索模式

提前谢谢


Tags: name列表字典模式平均值filebytesthisisname2thisisname1
2条回答

这是一个使用“memorybytes”键的示例

dic = [{"name": "thisisname1", "filebytes": 334632,"memorybytes": 5467234},{"name": "thisisname2", "filebytestotal": 2351, "memorybytes": 324523},{"name": "thisisname3", "filebytestotal": 2314651, "memorybytes": 2235},{"name": "thisisname1", "filebytestotal": 13432, "memorybytes": 546534},{"name": "thisisname1", "filebytestotal": 32342, "memorybytes": 341234}]

pattern_name = "1"
all_memorybytes = [element['memorybytes'] for element in dic if pattern_name in element['name'] ]
avg_memorybytes = sum(all_memorybytes) / float(len(all_memorybytes))
print avg_memorybytes

FileByTestTotal有一个问题,因为您有两个不同的键: “filebytes”和“filebytestotal”。如果你在数组的所有元素中都有这个键,那么你可以通过改变理解列表中的键来使用相同的功能

解决这个问题的一种方法是将它重组为一个列表字典。像这样的

list_of_dicts = [{"name": "thisisname1", "filebytestotal": 334632,"memorybytes": 5467234},    
{"name": "thisisname2", "filebytestotal": 2351, "memorybytes": 324523},    
{"name": "thisisname3", "filebytestotal": 2314651, "memorybytes": 2235},    
{"name": "thisisname1", "filebytestotal": 13432, "memorybytes": 546534},    
{"name": "thisisname1", "filebytestotal": 32342, "memorybytes": 341234}]

# reshape
from collections import defaultdict
dict_of_lists = defaultdict(list)
for obj in list_of_dicts:
    dict_of_lists[obj['name']].append({
        'bytestotal': obj['filebytestotal'],
        'memorybytes': obj['memorybytes'],
    })

dict_of_lists
> {'thisisname1': [{'bytestotal': 334632, 'memorybytes': 5467234}, ...], ...}

# and now calculate your averages
for key, totals_list in dict_of_lists.items():
    bytes_total = [obj['bytestotal'] for obj in totals_list]
    bytes_total_avg = sum(bytes_total) / len(bytes_total)
    print(key, bytes_total_avg)
    # and the same for memory bytes

这使用^{},它用默认值填充任何空键。你可以用内置字典来写,但这样可以省下几行

相关问题 更多 >