Python,如何从MySQL的元组中获得平均值?

时间:2018-06-15 20:19:20

标签: mysql python-3.x raspberry-pi3

我从MySQL中获取一些温度数据,我在这样的元组中收到这些数据: ((十进制(&#39; 28.7&#39;),),(十进制(&#39; 28.7&#39;),),(十进制(&#39; 28.6&#39;),))< / p>

我似乎无法弄清楚如何获得这些价值的平均值。

希望有人知道,这很容易解决? :)

有时这些元组包含更多数据,有时更少,但正如所说的目标是以某种方式获得平均值。

这是我现在的代码:

db = MySQLdb.connect("localhost","user","pass","weather")
cursor = db.cursor()
sql = "SELECT "+dbcolumn+" FROM weather_data WHERE DATETIME > NOW() - INTERVAL 15 MINUTE"
cursor.execute(sql)
fetched = cursor.fetchall()
cursor.close()
db.close()

#This prints out each item in the tuple nicely on separate rows
for i in fetched:
    print(i[0])

print("next is the average:")

#This currently prints the tuple, but should be modified to print the average of the tuple instead
print(fetched)

谢谢你们!

编辑:我最终创建了一个函数,它返回了元组的平均值。 这就是这个功能:

#This function finds the average in a tuple, as from the minutedata function
def averager(incoming):
    datasummary = 0
    itemsnumber = 0
    for i in incoming:
        datasummary = datasummary + i[0]
        itemsnumber = itemsnumber + 1
    dataaverage = datasummary / itemsnumber
    return dataaverage

2 个答案:

答案 0 :(得分:0)

如果您想在不提取数据的情况下获得平均值,可以直接在查询中使用AVG MYSQL function

答案 1 :(得分:0)

我最终创建了一个函数,它返回了元组的平均值。这就是函数:

#This function finds the average in a tuple, as from the minutedata function
def averager(incoming):
    datasummary = 0
    itemsnumber = 0
    for i in incoming:
        datasummary = datasummary + i[0]
        itemsnumber = itemsnumber + 1
    dataaverage = datasummary / itemsnumber
    return dataaverage