我是 Python 新手,偶然發現了以下問題:我有兩個串列(listA 和 listB)由元組('str',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)
任何人都可以幫忙嗎?非常感謝!
uj5u.com熱心網友回復:
使用 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
uj5u.com熱心網友回復:
試試下面的代碼:
sum = 0
ii=0
for sub in listA:
ii =1
i=sub[1]
sum = sum i
avg=sum/ii
uj5u.com熱心網友回復:
s = lambda x:[i[1] for i in x]
print(sum(s(listA))/len(listA))
print(sum(s(listB))/len(listB))
uj5u.com熱心網友回復:
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)
uj5u.com熱心網友回復:
兩個不同的點,每個點都有幾個解決方案。
一、如何從串列中的元組中取回浮點數
使用解包習語和串列理解
float_list = [v for i, v in listA]純Python
float_list = [] for item in listA: float_list.append(item[1])
二、如何計算平均值
mean從某個模塊匯入from Numpy import meanfrom statistics import mean
使用
sum和length對串列中的值求和并除以串列長度
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 的混合,但臨時解決方案可以省去中間串列的構建(float_list在第 I 部分的示例中)
例如:
使用
sum和length對串列中的解壓縮值求和并除以串列長度
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/353124.html
