简体   繁体   English

计算python中sqlite3的数据列表的平均值

[英]Calculating average of list of data from sqlite3 in python

I am trying to make a program that pulls a column of data from sqlite3 and use it to calculate different things (average, stdv, etc.) Here is what I have so far and the issue I am running into: 我正在尝试创建一个程序,从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)

I am receiving the following error: average = (sum(age_list))/len(age_list) TypeError: unsupported operand type(s) for +: 'int' and 'str' 我收到以下错误:average =(sum(age_list))/ len(age_list)TypeError:+:'int'和'str'的不支持的操作数类型

How can I correct the way I pull the data so I can calculate the average from it? 如何更正我拉取数据的方式,以便我可以从中计算平均值?

do this 做这个

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

lists are defaulted to strings and it is falling on you doing mathematical operations with them, by declaring them to integers then it knows you want them to be numbers. 列表默认为字符串,并且它依赖于你对它们进行数学运算,通过将它们声明为整数然后它知道你希望它们是数字。

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

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