我有以下格式的列表:
x = [["hello",0,5], ["hi",0,6], ["hello",0,8], ["hello",1,1]]
算法:
"hello",0,5
是与"hello",0,8
"hello",1,1
组合sum(all 3rd vals) / len(all 3rd vals)
all 3rd vals
是指每个内部重复列表的第3个值"hello",0,5
和"hello",0,8
变为hello,0,6.5
x = [["hello",0,6.5], ["hi",0,6], ["hello",1,1]]
问题:
如果不清楚,请告诉我,我会解释。
编辑:我试图将列表更改为一个集合以删除重复项,但是,这不能说明内部列表中的第三个变量,因此不起作用。
from collections import defaultdict
def avg(nums):
return sum(nums) / len(nums)
def func(lst):
third = defaultdict(list)
for sub in lst:
k = tuple(sub[:2])
third[k].append(sub[2])
lst_out = [[*k, avg(v)] for k, v in third.items()]
return lst_out
print(func(x)) # -> [['hello', 0, 6.5], ['hi', 0, 6.0], ['hello', 1, 1.0]]