python,如何从mysql的元组中得到平均值?

0s7z1bwu  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(500)

我正在从mysql中获取一些温度数据,这些数据以如下元组形式接收:((decimal('28.7'),),(decimal('28.7'),),(decimal('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)

谢谢你们!
编辑:我最终制作了一个函数,返回元组的平均值。。这就是功能:


# 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
fcy6dtqo

fcy6dtqo1#

最后我做了一个函数,返回元组的平均值。。这就是功能:


# 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
xkftehaa

xkftehaa2#

如果您想获得平均值而不获取数据,可以直接在查询中使用avg mysql函数

相关问题