亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Python 中以格式 (string, value) 獲取列表中每個元組的值的平均值

在 Python 中以格式 (string, value) 獲取列表中每個元組的值的平均值

鴻蒙傳說 2023-02-12 19:11:27
我有一個元組列表,例如:(A, 1), (B, 2), (C, 3), (A, 9), (B, 8).如何在不知道元組第一個元素的出現次數的情況下,獲取元組第一個元素的每個值的平均值?我想要這樣的東西:(A, 5), (B, 5), (C, 3).
查看完整描述

2 回答

?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

使用groupby和itemgetter:


from itertools import groupby

from operator import itemgetter

from statistics import mean



s = [('A', 1), ('B', 2), ('C', 3), ('A', 9), ('B', 8)]

s2 = sorted(s, key=itemgetter(0))   # sorting the tuple based on 0th index


print([(k, int(mean(list(zip(*g))[1]))) for k, g in groupby(s2, itemgetter(0))])

輸出:


[('A', 5), ('B', 5), ('C', 3)]


查看完整回答
反對 回復 2023-02-12
?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

from collections import defaultdict


sample = [("A", 1), ("B", 2), ("C", 3), ("A", 9), ("B", 8)]


store_alphabet_count = defaultdict(list)


for alphabet, count in sample:

    store_alphabet_count[alphabet].append(count)


result = [

    (key, sum(value) // len(value)) for key, value in store_alphabet_count.items()

]


print(result)

輸出:


[('A', 5), ('B', 5), ('C', 3)]


查看完整回答
反對 回復 2023-02-12
  • 2 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號