Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาค่าเฉลี่ยสะสม (Cumulative Mean) ของคีย์ใน Dictionary หลายตัว

โปรแกรมนี้รวมค่าของคีย์ที่ซ้ำกันในหลาย dictionary แล้วคำนวณค่าเฉลี่ย (mean) ของแต่ละคีย์ ใช้ statistics.mean()

ตัวอย่างโค้ด


from statistics import mean

dicts = [
    {'hi': 24, 'there': 81, 'how': 11},
    {'hi': 16, 'how': 78, 'doing': 63}
]

print("ลิสต์ Dictionary:", dicts)

# รวมค่าตามคีย์
combined = {}
for d in dicts:
    for k, v in d.items():
        if k in combined:
            combined[k].append(v)
        else:
            combined[k] = [v]

# คำนวณค่าเฉลี่ยแต่ละคีย์
for k, vals in combined.items():
    combined[k] = mean(vals)

print("\nค่าเฉลี่ยสะสมของแต่ละคีย์:")
print(combined)

ผลลัพธ์

ลิสต์ Dictionary: [{'hi': 24, 'there': 81, 'how': 11}, {'hi': 16, 'how': 78, 'doing': 63}]
ค่าเฉลี่ยสะสมของแต่ละคีย์:
{'hi': 20, 'there': 81, 'how': 44.5, 'doing': 63}

คีย์ 'hi' มีค่า 24 และ 16 -> mean = 20, 'how' มี 11 และ 78 -> mean = 44.5, คีย์ที่ไม่ซ้ำ ('there', 'doing') ค่าเฉลี่ยเท่าค่าเดิม