Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python - Trung bình cộng tích lũy của khóa Dictionary

Khi cần tìm trung bình cộng tích lũy của khóa dictionary, tạo dict rỗng, lặp dict gốc, truy xuất items. Nếu key đã có thì append giá trị, ngược lại tạo mới. Sau đó tính mean cho mỗi key.

Ví dụ

from statistics import mean

my_list = [{'hi': 24, 'there': 81, 'how': 11}, {'hi': 16, 'how': 78, 'doing': 63}]
print("The list is:")
print(my_list)

my_result = dict()
for sub in my_list:
    for key, val in sub.items():
        if key in my_result:
            my_result[key].append(val)
        else:
            my_result[key] = [val]

for key, my_val in my_result.items():
    my_result[key] = mean(my_val)

print("The result is:")
print(my_result)

Đầu ra

The list is: [{'hi': 24, 'there': 81, 'how': 11}, {'hi': 16, 'how': 78, 'doing': 63}]
The result is: {'hi': 20, 'there': 81, 'how': 44.5, 'doing': 63}

Giải thích

  • Nhập statistics.mean.
  • List of dicts, hiển thị.
  • Dict rỗng gom giá trị theo key.
  • Lặp list of dicts, gom giá trị cùng key vào list.
  • Tính mean cho mỗi key, cập nhật dict kết quả.
  • Hiển thị.