一段python从mysql数据库中取数据并且求平均值的代码

#encoding=gbk
import  sys
import  MySQLdb
import datetime
import time

dict = {"0":"0-0","1" : "0-500","2" : "500-700","3" : "700-900","4" : "900-1200",
        "5" : "1200-1600","6" : "1600-2000","7" : "2000-2500","8" : "2500-3000",
        "9" : "3000-3500","10" : "3500-4000","11" : "4000-5000","12" : "5000-7000",
        "13" : "7000-10000","14" : "10000-14999","15" : "15000-19999",
        "16" : "20000-29999","17" : "30000-49999",
        "18" : "50000-100000","19" : "100000-100000",}
city=["合肥","芜湖","蚌埠","六安","安庆",
      "淮南","马鞍山","淮北","铜陵","黄山",
      "滁州","阜阳","宿州","亳州","池州",
      "宣城"]
def getvalue(x):
  list=dict[x].split('-') #['0', '500']
  return list


#计算时间
starttime = datetime.datetime.now()



conn=MySQLdb.Connection('127.0.0.1','root','123456','job',charset='gbk')
cur=conn.cursor()

#循环输出所有城市
for ci in city:
    #去除空数据 & 面议数据 & 工作地点为空数据
    count=cur.execute("SELECT etjobsalary FROM demo_jobs_store\
                  WHERE etjoblocation_str LIKE '%%%s%%'"%ci)
    conn.commit()
    print "总记录:%s" %count

    #执行检查结果
    cur.scroll(0,mode='absolute')
    results=cur.fetchall()
    fields=cur.description
    low=0
    high=0
    i=0
    for ics in range(0,len(results)):
        a=int(getvalue(results[ics-1][0])[0])
        b=int(getvalue(results[ics-1][0])[1])
        if a<100000 and b<100000:
          low+=a
          high+=b

    print "%s的工资是:"%ci
    print int((low/count)*0.01)*100
    print int((high/count)*0.01)*100


    
#时间结束
endtime = datetime.datetime.now()
#输出时间
print (endtime - starttime).seconds

代码解释:

1、需要安装mysqldb for python的插件

2、该段代码的主要作用是从mysql数据库中字段取出数据,并且根据字段对应的值来取平均值


数据库截图:

一段python从mysql数据库中取数据并且求平均值的代码_第1张图片

结果输出如图:

一段python从mysql数据库中取数据并且求平均值的代码_第2张图片


总结:

1、该段代码用到了多种结构,例如list和dict等。

2、用到了函数。

3、用到了mysql的循环处理。

4、统计程序运行时间。


文章来自乐职网  http://www.lezhi.com/

你可能感兴趣的:(python/php/perl)