我在linuxmint上使用python3.4。SQL语句返回长列表中的数据库数据。我可以很好地循环列表,但需要正确格式化输出。我可以在列表中设置一个分隔符,例如“@”以指示行数据的结尾,但我不知道如何从列表中一次读回该数据(“@”表示行结束)。尝试使用split()但列表中的数据是混合的、整数值和字符串,所以split()失败。请帮忙!在
loop = 1
for data in orders: #loop all values returned (main loop)
#loop 1, set dupe-check variable
if data[0] not in cdupes:
cdupes.append(data[0]) #store customer name for next loop
if loop > 1:
rowdata.append("@")
for val in range(0, 4): #sql always returns 4 columns per row
rowdata.append(data[val]) #name, id, productline, ordertotal
#if customer name is a duplicate, append remaining customer productlines data
elif data[0] in cdupes: #customer name [0] in cdupes
for val in range(2, 4):
rowdata.append(data[val]) #store id, productline, ordertotal
loop += 1
print(rowdata)
我不确定我的问题是否清楚,但我已经解决了这个问题。我的SQL语句将返回customernames、customerid、productlines和productlinettls,即每个客户每个productline的总订单数。问题是SQL为每个客户返回多行,因为每个客户可能有多个productline。示例…
阿尔法干邑242经典车173998.00
阿尔法干邑242平面16655.22
阿尔法干邑242船18279.26
阿尔法干邑242老爷车8250.30
每一行都存储在list[]中,我需要删除重复的customer names+id,并将所有值以1列/行(每个cust)的格式存储,并将0.00放入productline:
示例:
CustName ID Cl Cars Bikes Planes Trains Ships Trucks&bus老式车
阿尔法干邑242 173998.00 0.00 16655.22 0.00 18279.26 0.00 8250.30
我在上面发布的代码将删除重复的custnames+id,并将数据重新构造为一个唯一的行,但没有丢失的列(例如自行车、火车等)。在
由于某些产品线没有可用的值,所以我需要插入这些值。我使用listcomparator获取productline值在唯一行中的位置的索引。
例子: productlines=['经典汽车','自行车','飞机','火车','轮船','卡车和公共汽车','老式','汽车']
这只是我用来解决这个问题的函数的节选。我希望这个想法可以帮助其他人,但我相信还有其他方法可以做到这一点。我对Python很陌生。在
相关问题 更多 >
编程相关推荐