2014-10-07 68 views
-1

我在Linux Mint上使用Python 3.4。 SQL语句以长列表形式返回DB数据。我可以循环遍历列表,但需要正确格式化输出。我可以在列表中设置一个分隔符,比如'@'来表示行数据的结尾,但是我不知道如何从列表中每次读取一行数据('@'表示结束行)。尝试使用split()但列表中的数据是混合的整数值和字符串,所以split()失败。请帮忙!Python使用分隔符分割整数和字符串(混合)列表?

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) 
+0

请告诉您希望输出什么类型。 – 2014-10-07 14:39:44

+0

为什么你需要读回输出?如果不打印给用户,可以使用[json](https://docs.python.org/3/library/json.html)等。 – parchment 2014-10-07 14:51:03

+0

由于我还不能发布图片,因此这里是我需要的输出链接http://genesis.kennesaw.edu/python_output.jpg。我需要阅读列表中代表数据行的部分,以便我可以操纵数据输出以看起来像从链接中看到的内容。与PyCharm列表输出的另一个链接http://genesis.kennesaw.edu/PythonList-with-Delimiter.jpg – maestro2mil 2014-10-07 15:22:52

回答

0

我不知道我的问题是否清楚,但我已经解决了这个问题。我的SQL语句将返回客户名称,客户名称,产品线和产品线,即每个客户每个产品线的总订单数。问题在于SQL为每个客户返回多行,因为每个客户可能有多个产品线。实施例...
阿尔法白兰地242经典汽车173998.00
阿尔法白兰地242架飞机16655.22
阿尔法白兰地242个船舶18279.26
阿尔法白兰地242老式汽车8250.30

每一行正在存储在列表中[]和我需要删除重复的客户名称+ ID和所有的值存储在一个1个COL /行(每CUST)格式,并把0.00其中用于PRODUCTLINE没有值:


的CustName ID氯汽车自行车飞机火车船舶卡车&公共汽车老爷车
阿尔法干邑242 173998.00 0.00 16655.22 0.00 18279.26 0.00 8250.30

我上面贴会删除重复的custnames + IDS和重构的代码数据到1个唯一行,但没有丢失列(即。自行车,火车等)。

由于没有可用于某些产品线的值,因此需要插入这些值。我使用了一个listcomparator来获取产品线值在唯一行中的位置的索引。
示例: 代理产品= [ '经典汽车', '自行车', '飞机', '火车', '船', '货车&公共汽车', '老式', '汽车']

for x in range(0, len(productlines): 
    try 
    idx = rowdata.index(productlinelines[]) #give me the index of productline if found 
    except ValueError: 
    row.append(format(0.00, '.2f')) #insert 0.00 if no productline in unique row 
    else: 
    row.append(format(rowdata[idx+1], '.2f')) #grab the value of the productline line and insert into correct column & format to 2 decimal 

这只是我用来解决这个问题的功能的摘录。我希望这个想法可以帮助其他人,但我相信还有其他方法可以做到这一点。我对Python很陌生。