[英]Perform operation on floats in list value that contains both floats and strings
[英]Printing the average of floats from a list that contains both floats and strings
我正在對收集到的推文進行情感分析,每個結果看起來像這樣,具體取決於推文的數量:
['pos', 0.8, 'neg', 1.0, 'pos', 1.0, 'pos', 1.0, 'pos', 1.0, 'pos', 1.0, 'neg', 1.0]
浮點數代表置信度%,我想從此列表中計算並打印所有平均值,但是我在此方面遇到了很多麻煩。
這是一種方法:
A = ['pos', 0.8, 'neg', 1.0, 'pos', 1.0, 'pos', 1.0, 'pos', 1.0, 'pos', 1.0, 'neg', 1.0]
res = sum(A[1::2]) / (len(A) / 2)
print(res)
0.9714285714285714
或者,如果您不想創建新列表:
from itertools import islice
res = sum(islice(A, 1, None, 2)) / (len(A) / 2)
另外,您也可以在標准庫中使用statistics.mean
:
from statistics import mean
res = mean(A[1::2])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.