2 回答

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)]

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)]
添加回答
舉報