简体   繁体   English

从包含浮点数和字符串的列表中打印浮点数的平均值

[英]Printing the average of floats from a list that contains both floats and strings

I'm performing sentiment analysis on Tweets I've collected, and each outcome looks like this, depending on the amount of tweets: 我正在对收集到的推文进行情感分析,每个结果看起来像这样,具体取决于推文的数量:

['pos', 0.8, 'neg', 1.0, 'pos', 1.0, 'pos', 1.0, 'pos', 1.0, 'pos', 1.0, 'neg', 1.0]  

The floats stand for the confidence%, and I want to calculate & print the average of all of them from this list, but I'm having quite some trouble with it. 浮点数代表置信度%,我想从此列表中计算并打印所有平均值,但是我在此方面遇到了很多麻烦。

This is one way: 这是一种方法:

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

Or if you would rather not create a new list: 或者,如果您不想创建新列表:

from itertools import islice

res = sum(islice(A, 1, None, 2)) / (len(A) / 2)

Alternatively, you can use statistics.mean , also in the standard library: 另外,您也可以在标准库中使用statistics.mean

from statistics import mean

res = mean(A[1::2])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM