2013-10-11 54 views
0

我在對齊結果值時遇到了問題。如何在Python中對齊結果值

Alist = ["1,25,999", 
    "123.4,56.7890,13.571", 
    "1,23.45,6,7.8"] 

c = 0 

while c < len(Alist): 
    r = 0 
    tokens = Alist[c].split(',') 

    while r < len(Alist[c].split(',')): 
     if '.' in tokens[r]: 
      print "%7.2f" %float(tokens[r]), " ", 
     else : 
      print "%3d" %float(tokens[r]), " ",  
     r += 1 
     print 

    c += 1 

我想打印如

1 25 999 
    123.40 56.79 13.57 
    1 23.45 6.  7.80 

但不知何故,它是印刷

1 
    25 
    999 
    123.40 
    56.79 
    13.57 
    1 
    23.45 
    6 
    7.8 

,我想不出有什麼不對我的編碼。

回答

0

r+1之後,你有一個單獨的打印語句。它處於錯誤的縮小級別 - 將它向左移動4個空格(或一個製表符),它應該可以正常工作。

0

print聲明應該不會在第二個while循環中。只是:

Alist = ["1,25,999", 
"123.4,56.7890,13.571", 
"1,23.45,6,7.8"] 

c = 0 

while c < len(Alist): 
    r = 0 
    tokens = Alist[c].split(',') 

    while r < len(Alist[c].split(',')): 
     if '.' in tokens[r]: 
      print "%7.2f" %float(tokens[r]), " ", 
     else : 
      print "%3d" %float(tokens[r]), " ",  
     r += 1 
    print 

    c += 1 
0
In [59]: %paste 
myList = ["1,25,999", 
    "123.4,56.7890,13.571", 
    "1,23.45,6,7.8"] 
rows = [r.split(',') for r in myList] 
widths = {i:max(len(c) for c in col) for i,col in enumerate(itertools.izip_longest(*rows, fillvalue=""))} 
for row in rows: 
    for i,val in enumerate(row): 
    print " "*((widths[i] - len(val))/2), val, " "*((widths[i] - len(val))/2) if not (widths[i]-len(val))%2 else " "*((widths[i] - len(val)+1)/2), 
    print 

## -- End pasted text -- 
    1  25  999 
123.4 56.7890 13.571 
    1  23.45  6  7.8