python - 在python中计算来自sqlite3的数据列表的平均值

标签 python sqlite

我正在尝试制作一个程序,从 sqlite3 中提取一列数据并使用它来计算不同的东西(平均值、stdv 等) 这是我目前所拥有的以及我遇到的问题:

from math import *
import sqlite3
conn = sqlite3.connect('personinfo.sqlite3')

def main():
    ages_iterator = conn.execute("SELECT age from person")
    age_list = [a[0] for a in ages_iterator]

    # average age
    average = (sum(age_list))/len(age_list)

我收到以下错误: 平均值 = (sum(age_list))/len(age_list) 类型错误:+ 不支持的操作数类型:“int”和“str”

如何更正提取数据的方式,以便从中计算平均值?

最佳答案

这样做

age_list = [int(a[0]) for a in ages_iterator]

列表默认为字符串,它落在你对它们进行数学运算的任务上,通过将它们声明为整数然后它知道你希望它们是数字。

关于python - 在python中计算来自sqlite3的数据列表的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40635442/

相关文章:

python - 使用 Python 进行字符翻译(如 tr 命令)

python - 在 Pandas 中,如何用数据帧的另一个子集替换数据帧的一个子集?

Python sqlite - 在 execute() 方法中引用用法

python - 如何使用 msvc 10.0 为 win8.1 64 位构建 boost python 3.4 共享库

Python/Datetime/Pandas - 更改日期时间格式

python - 在 Python 中使用中文

python - 处理巨大的 bz2 文件

android - 使用 alertdialog 构建器的 setCursor 方法显示数据库中的项目列表时如何添加多个列?

sql - 获取特定或其他语言的页面数据

javascript - 使用JS向SQLite插入字符串没有语法错误