计算元组列表中数值的平均值



我是Python的新手,偶然发现了以下问题:我有两个列表(listA和listB(,由元组('str',float(组成,我必须计算每个列表的float值的平均值。

groups = ['A', 'B', 'B', 'A', 'B', 'B', 'B', 'B', 'A', 'A']
scores = [0.2, 0.3, 0.9, 1.1, 2.2, 2.9, 0.0, 0.7, 1.3, 0.3]
list_groups_scores = list(zip(groups,scores))
list_groups_scores.sort()

print(list_groups_scores)

listA = list_groups_scores[0:4]
listB = list_groups_scores[5:9]
print(listA, listB)

有人能帮忙吗?非常感谢!

使用dict保存组和分数

from collections import defaultdict
groups = ['A', 'B', 'B', 'A', 'B', 'B', 'B', 'B', 'A', 'A','K']
scores = [0.2, 0.3, 0.9, 1.1, 2.2, 2.9, 0.0, 0.7, 1.3, 0.3,1]
data = defaultdict(list)
for g,s in zip(groups,scores):
data[g].append(s)
for grp,scores in data.items():
print(f'{grp} --> {sum(scores)/len(scores)}')

输出

A --> 0.725
B --> 1.1666666666666667
K --> 1.0

尝试以下代码:

sum = 0
ii=0
for sub in listA:
ii+=1
i=sub[1]
sum = sum + i
avg=sum/ii
s = lambda x:[i[1] for i in x]
print(sum(s(listA))/len(listA))
print(sum(s(listB))/len(listB))

python中有一种特殊类型的循环,看起来像这样。

listANumbers = [i[1] for i in listA]

它循环遍历listA中的每个元素,并将每个元素[1]设置为一个新列表。

结果:

[0.2, 0.3, 1.1, 1.3]

然后你可以得到新列表的总和和平均值。

listANumbers = [i[1] for i in listA]
meanA = sum(listANumbers) / len(listANumbers)

两个不同的点,每个点都有几个解决方案。

I。如何从列表中的元组返回浮点值

  • 使用解包习语和列表理解

    float_list = [v for i, v in listA]
    
  • 纯Python

    float_list = []
    for item in listA:
    float_list.append(item[1])
    

II。如何计算平均值

  • 从某个模块导入mean

    • from Numpy import mean
    • from statistics import mean
  • 使用sumlength

    对列表中的值求和并除以列表长度

    mean = sum(v in a_list) / len(a_list)
    
  • 纯Python

    循环到聚合值和计数到长度

    aggregate = 0
    length = 0
    for item in a_list:
    aggregate += item
    length += 1
    mean = aggregate / length    
    

    注:选择aggregate有两个原因:

    - avoiding the use of a built-in function
    - generalizing the name of the variable, for example, a function other than addition could be used.
    

解决方案

解决方案可以是步骤I和步骤II的混合,但ad'hoc解决方案可以省去中间列表的构建(第一部分示例中的float_list(

例如:

  • 使用sumlength

    对列表中未打包的值求和,然后除以列表长度

    mean = sum(v in float_list) / len(float_list)
    

    注意:v in float_list不创建列表;它是一个生成器,根据需要提供浮动。

  • 纯Python

    循环到聚合值和计数到长度

    aggregate = 0
    length = 0
    for item in  listA:
    aggregate += item[1]
    length += 1
    mean = aggregate / length 
    

最新更新