最近测试接口遇到一个问题,用python2.7从mysql中取到的数据是元祖类型的,元祖内部的元素也是一个元祖(并且部分元素的编码格式是unicode的);
类似这样:
((10144, u''), (50016, u'[10029,50042,10189,50044]'), (10155, u'[10048]'), (10069, u'[50030,10133]'), (10029, u''), (0, u''), (10128, u''), (10189, u'[50041,50016,50043]'), (50036, u''), (0, u''), (50017, u''))
我的需求是把所有5位数的数字组成一个列表,数据处理的过程很有趣,记录一下。
代码实现:
# coding: utf-8
import pymysql
import re
#链接数据库、执行SQL
def accountuser():
# 创建一个连接对象,再使用创建游标
con = pymysql.connect(host='100.30.0.20', port=3306, user='user', passwd='M20000000', db='chip_service_sole',charset='utf8')
cursor = con.cursor()
# 执行SQL
sql = 'select karAccount,authorizedAccount from device where appkey like "bmgfkakicb2et243usfbizdt45mp6utbtb3433il"'
cursor.execute(sql)
# 从游标中取出所有记录放到一个序列中并关闭游标
result = cursor.fetchall()
cursor.close()
# 元祖类型result转换成列表类型result
result = list(result)
return result
# 去除列表中account为0的元素
def withoutzero():
result1 = accountuser()
asd = (0, u'')
for i in result1:
if i == asd:
f = result1.index(i)
result1.pop(f)
return result1
# 把列表转换为str类型,并生成只包含所有account的字符串
def changstr():
result2 = str(withoutzero())
result2 = result2.strip('[').strip(']')
result2 = re.sub("[(u')]", '', result2)
result2 = re.sub("[ []", '', result2)
result2 = re.sub("[],]", '', result2)
return result2
# 创建包含所有account的列表
def creatlist():
result3 = changstr()
listnew = []
for i in range(len(result3) / 5):
j = result3[:5]
result3 = result3[5:]
listnew.append(j)
print listnew
print len(listnew)
# 主函数
def run():
result = accountuser()
if len(result) > 0:
creatlist()
else:
print "查询到的account个数为0"
if __name__ == '__main__':
run()