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

Python, How do I get the average from a tuple from MySQL?

我正在从 MySQL 获取一些温度数据,我在这样的元组中接收到这些数据: ((小数('28.7'),), (小数('28.7'),), (小数('28.6'),))

我似乎无法弄清楚如何计算这些值的平均值。

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

有时这些元组包含更多数据,有时更少,但如前所述,目标是以某种方式得出平均值..

这是我目前的代码:

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)

谢谢大家!

编辑:我最终创建了一个函数 returns 我取而代之的是元组的平均值。 这是那个函数:

#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

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

我最终创建了一个函数,returns 我取的是元组的平均值。这就是那个函数:

#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