from math import *
import sqlite3
ages=sqlite3.connect('person.sqlite3')
def main():
ageslist=ages.execute("SELECT age from person")
#average age
for row in ageslist:
row[0]
average = (sum(row[0]))/len(row[0])
#subtracts average x from x or opposite and square, depending on n
for n in range(len(ageslist) - 1):
if numbers[n] > average:
numbers.append((ageslist[n] - average)**2)
if numbers[n] < average:
numbers.append((average - ageslist[n])**2)
#takes square rt of the sum of all these numbers and divides by n-1
Stdv = math.sqrt(sum(ageslist))/(len(ageslist)-1)
end=time()
print(Stdv)
main()
我正在尝试从SQLITE3数据库中找到年龄的标准偏差。但是,我得到当前错误:
平均=(sum(row [0]))/ len(row [0])
TypeError:“ int”对象不可迭代
我该如何纠正?
最佳答案
发送到数据库连接的查询返回一个迭代器。在从内存中刷新该迭代器之前,您只能传递一次。这是对代码的一些更正,以执行您要执行的操作。
conn = sqlite3.connect('person.sqlite3')
def main():
ages_iterator = conn.execute("SELECT age from person")
# this turns the iterator into an actual list, which you need for stdev
age_list = [a[0] for a in ages_iterator]
# average age
average = (sum(age_list))/len(age_list)
# subtracts average x from x square
# because you are squaring the difference, the it does not matter if it is
# greater or less than the average
numbers = [(age-average)**2 for age in age_list]
#takes square rt of the sum of all these numbers and divides by n-1
Stdv = math.sqrt(sum(numbers))/float(len(numbers)-1)
end=time()
print(Stdv)
main()
关于python - 用于标准偏差的Python代码以及来自SQLITE3的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40600077/