2012-05-16 39 views
3

我有以下解釋:循環通過詞典和一定的格式打印出來

# a small DB of people who stole my books 

dic = { 
'Cohen'  : 'Calvino' 'Evertt' 'Borges', 
'Larry'  : 'The Bible', 
'Volanski' : 'Phone Book' 
} 

# here's an abortive attempt to print it in a CSV format 
for k in dic.keys(): 
    print (k, '\t') 
for v in dic.keys(): 
    print (dic[v], ' ') 

這是醜陋的輸出:

Volanski  
Phone Book 
CalvinoEverttBorges 
The Bible 
Cohen 
Phone Book 
CalvinoEverttBorges 
The Bible 
Larry 
Phone Book 
CalvinoEverttBorges 
The Bible 

這是怎麼我祝願輸出看起來像:

Cohen  Larry  Volanski 
Calvino The Bible Phone Book 
Evertt 
Borgest 

(只有製表符分隔,我沒有在這裏顯示)

+0

沒錯,這就是我怎麼想它的樣子;)感謝,菲利克斯! – nobo

+0

首先,使用列表,比如'['Calvino','Evertt','Borges']' – FallenAngel

回答

2

您可以制定出更簡潔的格式

dic = {'Cohen'  : ['Calvino', 'Evertt', 'Borges'], 
     'Larry'  : ['The Bible'], 
     'Volanski' : ['Phone Book']} 

# Get max name size 
mx_nm_len = len(max(dic,key=len)) 
mx_bk_len = max([len(max(books, key=len)) for books in dic.itervalues()]) 

# Store max name size + 1 
mx = max([mx_nm_len, mx_bk_len]) + 1 

# Store people 
keys = dic.keys() 

# Create generic format code to print neat list 
fmat = ("%-"+str(mx)+"s")*len(keys) 

# Print header line 
print fmat % tuple(keys) 

# similar to zip command but works for any number of lists 
# Assumes all dic.values() are lists 
# "zips" to longest list and uses None when any given list runs out of values 
books = map(None, *dic.values()) 

# replaces None values in row outputs with empty strings and prints result using 
# string format code (fmat) 
for row in books: 
    row = tuple([book if book!= None else "" for book in row]) 
    print fmat % row 
+0

非常整齊,非常感謝你的評論,否則我不會理解代碼! – nobo

+0

沒有問題很高興它的幫助。 「最棘手」的一點是我對地圖功能的使用。增加了更多評論來幫助解釋其目的。 –

1

問題是您沒有以正確的方式定義數據。 Python定義第一個條目的方式正好與它的打印方式相同:單個字符串。如果你想多個元素,你需要定義元素包含多個元素:

dic = { 
    'Cohen'  : ['Calvino', 'Evertt', 'Borges'], 
    'Larry'  : ['The Bible'], 
    'Volanski' : ['Phone Book'] 
} 

現在,你可以簡單地這樣做:

for key, value in dic.items(): 
    print "%s\t%s" % (key, "\t".join(value)) 

編輯 OK,沒看到你想要的頂部名稱和標題向下。麻煩一點,但是這將做到這一點:

import itertools 
print "\t".join(dic.keys()) 
for books in itertools.izip_longest(*dic.values(), fillvalue=''): 
    print "\t".join(books) 
+0

我明白了。但輸出看起來現在行格式,而不是在列:Volanski \t電話簿 科恩\t卡爾維諾\t Evertt \t博爾赫斯 拉里\t聖經 – nobo

+0

@nobo看到我的更新。 –

+0

好的解決方案,但空行導致一個轉變...使用'ljust'可能是一個固定的填充評估從值中最長的字符串... – FallenAngel

2
dic = { 
    'Cohen'  : ['Calvino', 'Evertt', 'Borges'], 
    'Larry'  : ['The Bible'], 
    'Volanski' : ['Phone Book'] 
} 


ordered = [] 
maxlen = 0 

for k in sorted(dic.keys()): 
    lst = [k] + dic[k] 
    maxlen = max(len(lst), maxlen) 
    ordered.append(iter(lst)) 

for i in range(maxlen): 
    print "\t".join(next(j, '') for j in ordered) 
+0

字典鍵應該可能被排序,python不保證排序順序。你可以用itertools做這個清潔工,但是再次錯過所有的樂趣和理解:D –

+0

非常感謝我學到了一些東西! – nobo

0

該解決方案可確保輸出的排序和物品在正確列拉閘。我使用expandtabs()來設置標籤的長度,以使它更漂亮。

import itertools 

dic = {'Cohen':['Calvino', 'Evertt','Borges'],'Larry': ['The Bible'], 'Volanski' :['Phone Book']} 

sorted_keys = sorted(dic.keys()) 
for name in sorted_keys: 
    print (name+'\t').expandtabs(15), 
print 
zippp = list(itertools.izip_longest(*[dic[i] for i in sorted_keys])) 
for i in xrange(len(zippp[0])): 
    for j in xrange(len(zippp)): 
     if zippp[i][j]: 
      print (zippp[i][j]+'\t').expandtabs(15), 
    print 

產地: